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; }
The substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive).
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
The difference between substring() and substr() The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .
Substring in C++ A function to obtain a substring in C++ is substr(). This function contains two parameters: pos and len. The pos parameter specifies the start position of the substring and len denotes the number of characters in a substring.
If I am correct, the second parameter of substr()
should be the length of the substring. How about
b = a.substr(i,2);
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With