Drop letters except numbers with cin

I have this loop right now that reads in numbers and prints them in decimal, octal and hexadecimal values:

while(1) { if (cin >> n) cout << internal << setfill(' ') << setw(10) << dec << n << internal << setw(12) << oct << n << internal << setw(9) << hex << uppercase << n << endl; if (cin.fail()) { break; } } 

However, if I try to discard input that is not numbers, this will not be read in the input after the letters:

 if (cin.fail()) { cin.ignore(); } 

How to reset input, but can you read other data later?

Input Example:

 23 678 786 abc 7777 

Expected Result: dec, oct, hex


  23 27 17 678 1246 2A6 786 1422 312 7777 17141 1E61 
+6
source share
1 answer

You need to destroy the offensive content from cin and reset the error state. As long as failbit installed, all input operations immediately fail.

 while(1) { if (cin >> n) cout << internal << setfill(' ') << setw(10) << dec << n << internal << setw(12) << oct << n << internal << setw(9) << hex << uppercase << n << endl; else { if (cin.eof()) break; cin.clear(); // Reset the error state std::string dummy; if (!(cin >> dummy)) // Consume what ever non-integer you encountered break; } } 

Alternatively, you can always read std::string , and then try to parse this number with std::stoi :

 for (std::string word; std::cin >> word;) { try { int n = std::stoi(word); // You output logic here } catch (std::exception&) {} } 

But this is likely to abuse the exceptions, since you are claiming that invalid input is not exclusive. On the other hand, this means doing less logic manually.

+2
source

All Articles