Reputation: 57
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.
Upvotes: 0
Views: 306
Reputation: 15521
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.";
}
}
Upvotes: 1