简体   繁体   中英

Reading 500 inputs on one line via std::cin produces garbage

I have a very simple program:

int n;
int arr[1000];
cin >> n;
for (int i = 0; i < n; i++) {
    cin >> arr[i];
}

This works as expected for small inputs, but as soon as n > ~500 the input turns into upside down question marks as I type. It seems like the fact that the input is separated by spaces makes a difference because if I input 250 numbers, hit return, and then enter the next 250 numbers it works as expected.

Anyone know why this is happening?

EDIT: Thanks for the advice on checking to see if my terminal is borked; it turns out it is. Just running ./a.out < input.txt instead of trying to run the program via Xcode makes everything work fine using the exact same input.

"... if I input 250 numbers, hit return, and then enter the next 250 numbers it works as expected. ..."

Doing so sounds pretty error prone for simple typos in input or such. Manually typing in that large amount of numbers is likely to fail from a strayed unwanted character or such.

You should check the actual results of the input

 while(!(cin >> arr[i])) {
     cin.clear();
     std::string dummy;
     cin >> dummy;
     cerr << "Invalid input: '" << dummy << "'." << endl;
 }

or simply stop processing in case of errors encountered:

if(!(cin >> arr[i])) {
     cin.clear();
     std::string dummy;
     cin >> dummy;
     cerr << "Invalid input: '" << dummy << "'." << endl;
     break;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM