使用getch后如何在另一个字符串的末尾连接一个字符串

How to concatenate a string at the end of another string after using getch

对于此代码:

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

Input: 12345, then Enter key


Output: xyz45


如何阻止这种情况发生?


Desired output: 12345xyz


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

while ((c = getch()) != '\r')
    a += c;