1

对于此代码:

#include <iostream>
#include <string>
#include <conio.h>

int main()
{
    std::string a;
    char c{};
    while (c != '\r')
    {
        c = getch();
        a += c;
    }
    a += "xyz";
    std::cout << a;
}

输入:12345,然后Enter


输出:xyz45


我该如何阻止这种情况发生?


期望的输出:12345xyz


4

1 回答 1

3

您需要避免\r在字符串中添加字符,例如:

while ((c = getch()) != '\r')
    a += c;
于 2020-06-06T16:39:18.617 回答