Search code examples
c++stringfor-loopintgetline

String to int and again to string C++


i want to program take a string from user and convert it to some numbers(characters), and when numbers increased by 1 unit then put them in an other string and show it.

    string text, code;

    cout << "Enter Text: ";
    getline(cin, text);

    for (int i = 0; i < 8 ; i++)
        code[i] = text[i] + '1';
    cout<<code<<endl;

for example if i entered as blow: abcd123 result be as blow: bcde234

but when i run this, after my input it gets an error :(


Solution

  • The reason for the error is that the string code is unitialised, and accessing it at index i is UB. To fix this, add the following line after reading the input and putting it in the string text

    code = text; // Giving it the exact value of text is redundant. The main point is to initialise it to appropriate size.
    

    Besides that, instead of

    code[i] = text[i] + '1';
    

    It should be

    code[i] = text[i] + 1;
    

    You could also modify the code as follows to avoid the code variable and make it more concise:

    text[i]++;