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;
}
substr(i,j)
means that you start from the indexi
(assuming the first index to be 0) and take nextj
chars. It does not mean going up to the indexj
.If I am correct, the second parameter of
substr()
should be the length of the substring. How about?
Possible solution without using
substr()
Another interesting variant question can be:
How would you make
"12345"
as"12 23 34 45"
without using another string?Will following do?
You can get the above output using following code in c
As shown here, the second argument to
substr
is the length, not the ending position:Your line
b = a.substr(i,i+1);
will generate, for values ofi
: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 usingatoi()
on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:In fact, the entire thing could be more simply written as: