How to use string.substr() function?

VaioIsBorn picture VaioIsBorn · Mar 19, 2010 · Viewed 167k times · Source

I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
    string a;
    cin >> a;
    string b;
    int c;

    for(int i=0;i<a.size()-1;++i)
    {
        b = a.substr(i,i+1);
        c = atoi(b.c_str());
        cout << c << " ";
    }
    cout << endl;
    return 0;
}

Answer

Ghislain Fourny picture Ghislain Fourny · Mar 19, 2010

If I am correct, the second parameter of substr() should be the length of the substring. How about

b = a.substr(i,2);

?