c++stringgetchconio

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


For this code:

#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


How do I stop this from happening?


Desired output: 12345xyz



Solution

  • You need to avoid adding \r character to the string, something like:

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