-1

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];
}
  • 2
    Since you are using C-Strings, you are missing the terminating `\0'` character. – Thomas Matthews Jan 24 '22 at 21:06
  • Fair warning when fixing that. If you really intended to capture up to 21 keystrokes, you're going to need a bigger boat. You must also have a slot available for the terminating nullchar, so `word` should be 22 wide (or wider), not 21. – WhozCraig Jan 24 '22 at 21:27
  • I forget to mention, but the word only can have 20 characters, so the 21 position is for the \0'. Correct me, if I'm wrong. Thanks. – Facundo Borrás Jan 24 '22 at 21:27
  • @WhozCraig yes, your right. I'm aware of that but I completely forgot it. Thanks – Facundo Borrás Jan 24 '22 at 21:30
  • If the word can only have 20 characters, the loop from `i=0; i<21` is wrong. That iterates 21 cycles; not 20. – WhozCraig Jan 24 '22 at 21:31

1 Answers1

0

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).

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • Thanks for replying. I see, but it has to be an array yes or yes. Using your example I would do "c = getch()" and it will work. But if I do the same with an array It won't "char c[21];" and then "c = getch()" And I would like to know why it doesn't work. – Facundo Borrás Jan 24 '22 at 21:24
  • @FacundoBorrás `c = ...` doesn't work because (a) arrays in C are non-assignable lvalues, and (b) `getch` returns `char`, not an array, so the concept is nonsense regardless. – WhozCraig Jan 24 '22 at 21:28
  • If you want to input to a slot in a character array, use `std::cin >> word[i];`. – Thomas Matthews Jan 24 '22 at 21:31
  • @WhozCraig okay okay, I'm getting it. I didn't know. Thanks for your answer. – Facundo Borrás Jan 24 '22 at 21:33