How to use string.substr() function?

后端 未结 7 520
夕颜
夕颜 2020-11-29 06:40

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 su

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 06:41

    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 
    #include 
    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;
    }
    

提交回复
热议问题