Search code examples
c++arraysinputgetch

For some reason, when i use getch() my program crash, but if i use cin, then it works


I would like to know what knowledge I lack about inputs of arrays. I want to input one character and then automatically go to the next line of the code.

Here is the code:

char word[21];
for(int i = 0;i < 21; i++)
{
    word[i] = getch();
    //cin>>word[i];
    if(word[i] == '/')break;
}
for(int j = 0;j < strlen(word); j++ )
{
  if(j < (strlen(word) - 1 ))cout<<word[j];
}

Solution

  • Here's how I would do this:

    char c;
    std::cin >> c; // Input the character.
    std::cin.ignore(10000, '\n'); // Ignore remaining characters on the line.
    

    You could replace 10000 with the maximum value for unsigned integers, but I just use an improbable large number (to fuel the improbability drive).