字符串转换为int,再次转换为字符串C++

String to int and again to string C++

本文关键字:字符串 转换 C++ int      更新时间:2023-10-16

我想用程序从用户那里获取一个字符串,并将其转换为一些数字(字符),当数字增加1个单位时,将它们放在另一个字符串中并显示出来。

    string text, code;
    cout << "Enter Text: ";
    getline(cin, text);
    for (int i = 0; i < 8 ; i++)
        code[i] = text[i] + '1';
    cout<<code<<endl;

例如,如果我输入为blow:abcd123结果是:bcde234

但是当我运行这个程序时,在我的输入之后,它会得到一个错误:(

错误的原因是字符串code是统一的,在索引i访问它是UB。要解决此问题,请在读取输入并将其放入字符串text 后添加以下行

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

除此之外,代替

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

应该是

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

您也可以如下修改代码,以避免code变量,并使其更加简洁:

text[i]++;