While input is a letter this works fine but if I input a float number, for example 5.5 it stops. The question is how can I check if a float or double is entered?
int main(){
int a;
cout<<"enter a number:"<< endl;
while(!(cin>>a)) {
cin.clear();
cin.ignore(256,'\n');
cout << "wrong input\n";
}
}
CodePudding user response:
You might try something like this:
#include <iostream>
#include <cmath>
int main()
{
double in;
double ceil_in;
double diff;
do {
while (!(std::cin >> in))
{
std::cin.clear();
std::cin.ignore(123, '\n');
}
ceil_in = ceil(in);
diff = in - ceil_in;
} while(diff != 0.0);
std::cout << "Finish." << std::endl;
return 0;
}
Now it should work with strings too. Let me know if it addresses your problem.
CodePudding user response:
Just read whole line then try read integer from it checking if everything was read.
bool scan_int(const std::string& s, int& x) {
std::istringstream in{s};
return in >> x >> std::ws && in.eof();
}
int main()
{
std::string s;
while(std::getline(std::cin, s)) {
int x;
if (scan_int(s, x)) {
std::cout << "Integer found: " << x << '\n';
} else {
std::cout << '"' << s << "\" is not an integer\n";
}
}
return 0;
}
https://godbolt.org/z/xdcjzrEEd
CodePudding user response:
Two questions in one!
- How do I repeat some code multiple times?
- How do I read an integer from standard input?
This answer attempts to separate those 2 questions and also to show an extendable approach, just in case your next homework assignment will be to read not an int but a float or a hex number or 5 integers or whatever... and maybe from a file and not standard input...
For question 1, see main()
in the code below, for question 2, see read_fixnum()
.
#include <iostream>
#include <regex>
#include <string>
bool read_fixnum(std::istream& is,
std::string prompt,
int& result) {
std::regex fixnum{"\\s*(\\d )\\s*"};
std::cout << prompt << std::endl;
std::string line;
if (std::getline(is,line)) {
std::smatch match_result;
if (std::regex_match(line, match_result, fixnum)) {
result = std::stoi(match_result.str());
return true;
}
}
return false;
}
int main(int argc, const char* argv[]) {
int number = 0;
bool running = true;
while (running) {
if (read_fixnum(std::cin,
"enter an integral number: ",
number)) {
running = false;
}
}
std::cout << "you entered: " << number << std::endl;
return 0;
}