-3

I'm pretty new to coding so I apologize if this is trivial. I'm supposed to create an error message when the user enters more characters than my const int SIZE2 array, which is 20 characters. My array is called major:

>cout << "Enter your major: " << endl << endl;
>48         cin.width(SIZE2);
>49         cin.get(major,SIZE2, '\n');
>50         majorLength = strlen(major);
>51         
>52         if(majorLength > SIZE2)
>53         {   
>54             cout << "Too many characters, Enter major again: " << endl;
>55             cin.get(major, SIZE2, '\n');
>56             cin.ignore(100, '\n');
>57          
>58         }

It's compiling just fine but skipping over my if-statement.

Kevin
  • 16,549
  • 8
  • 60
  • 74
  • 2
    once you read the input into something that can only hold 20 characters, checking if it is more than 20 characters does not help anymore. Please provide a [mcve] (only some bits are missing, but details do matter) – 463035818_is_not_an_ai Oct 18 '19 at 19:46

1 Answers1

1

iostream.get() (here invoked as cin.get()) reads an exact number of bytes and then ends. In your case, it will specifically never read more than SIZE2 bytes into major; as a result, if(majorLength > SIZE2) will always be false. Also, if you enter too many bytes, major will only have the first 20 - the rest are truncated. (FWIW, your code is only matching 19 characters right now.)

Note that you probably shouldn't try to do this - there's not really a good way to check the length of a stream before you read it, and if you decide to just read it all and then check its size, you run the risk of overflowing your buffer - assuming it's fixed size.

You can, however, determine if, after reading, the buffer is empty or not. To determine if there is any more input in the buffer beyond SIZE2, you can capture one character with std::cin.get() and then examine this character. If the character is \n, it means there was no more input in the buffer; if it is not, that means the character buffer had too much input in it. This will also trigger if the input is completely blank.

#include <iostream>     

int main () {
  int SIZE2 = 20;

  char str[SIZE2];
  char c;

  std::cin.get (str, SIZE2+1);    // get c-string of 20 chars
  std::cin.get(c); //get last buffer character

  if(c != '\n') {
    std::cout << "bad input!" << std::endl;
  }

  std::cout << str << std::endl;
  return 0;
}

Demo

Nick Reed
  • 4,989
  • 4
  • 17
  • 37