0

I'm a beginner in C++ and I'm wondering if you can help me.

I'm making a program and error checking is required for this program. So, how can I accept integer only and ignore other data type?

For example:

int tilenumber; cin >> tilenumber; cin.clear(); cin.ignore(); cin >> words; 

When my code runs:

Input : 1 hey i wanna dance

Output : ey i wanna dance

///

What I want:

Case 1: Input : 1

hey i wanna dance

Output : hey i wanna dance

Case 2: Input : 1e

hey i wanna dance

Output : hey i wanna dance

Why does my code not working?

I tried to solve my problem with my code like above but it's not working.

Thanks.

4
  • 2
    Can you show us an MCVE? Commented Sep 21, 2017 at 13:38
  • 1
    Read all data as strings. Then check the content of the strings to extract integral values, and discard anything else you don't need. C++ I/O functions won't do that sort of checking for you - if you need it, you have to read the input and check it yourself. Commented Sep 21, 2017 at 13:39
  • thank you! @Peter I'll give it a try Commented Sep 21, 2017 at 13:43
  • cin >> tilenumber sets cin's failbit state if the conversion fails. Always check the stream's state after extracting input, eg: if (cin >> tilenumber) { use tilenumber ... } else { error ... } Commented Sep 21, 2017 at 16:20

1 Answer 1

1

Read the entire string and utilize the std::stoi function:

#include <iostream> #include <string> int main() { std::cout << "Enter an integer: "; std::string tempstr; std::getline(std::cin, tempstr); try { int result = std::stoi(tempstr); std::cout << "The result is: " << result; } catch (std::invalid_argument) { std::cout << "Could not convert to integer."; } } 

Alternative is to utilize the std::stringstream and do the parsing:

#include <iostream> #include <string> #include <sstream> int main() { std::cout << "Enter an integer: "; std::string tempstr; std::getline(std::cin, tempstr); std::stringstream ss(tempstr); int result; if (ss >> result) { std::cout << "The result is: " << result; } else { std::cout << "Could not convert to integer."; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.