views:

447

answers:

3

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;
}
+11  A: 

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

b = a.substr(i,2);

?

xqib-team
Yeah, he's incrementing the length of the substring each time.
smoore
+1, good observation!
Rajendra Kumar Uppal
+3  A: 

As shown here, the second argument to substr is the length, not the ending position:

string substr ( size_t pos = 0, size_t n = npos ) const;
Generate substring
Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position pos and has a length of n characters.

Your line b = a.substr(i,i+1); will generate, for values of i:

substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45  (since your string stops there).

What you need is b = a.substr(i,2);

You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45 due to the fact that you're using atoi() on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:

b = a.substr(i,2);
cout << b << " ";

In fact, the entire thing could be more simply written as:

#include <iostream>
#include <string>
using namespace std;
int main(void) {
    string a;
    cin >> a;
    for (int i = 0; i < a.size() - 1; i++)
        cout << a.substr(i,2) << " ";
    cout << endl;
    return 0;
}
paxdiablo
+1  A: 

Another interesting variant question can be:

How would you make "12345" as "12 23 34 45" without using another string?

Will following do?

    for(int i=0; i < a.size()-1; ++i)
    {
        //b = a.substr(i, 2);
        c = atoi((a.substr(i, 2)).c_str());
        cout << c << " ";
    }
Rajendra Kumar Uppal