The program should write an error if the user enters a fraction or decimal number
int a; if (int (a) == double (a)){ cout<<"error"; } For example user
entered the number 3 program it (skips)
3.2 then wrote (error)
The program should write an error if the user enters a fraction or decimal number
int a; if (int (a) == double (a)){ cout<<"error"; } For example user
entered the number 3 program it (skips)
3.2 then wrote (error)
For a single case, as you described:
cin >> a; if (char(cin.peek()) == '.') cerr << "error\n"; But I will add on my own complexity. It is better to make enter until a whole is entered:
int a{}; while(true) { cin >> a; if (char(cin.peek()) == '.') { //если после целого есть точка cerr << "error\n"; cin.ignore(); // пропускаем точку cin >> a; // читаем дробную часть } else break; } cout << "a == " << a; Update:
Or if we want to pass a number as a function argument:
#include <iostream> #include <sstream> using namespace std; void get_int(double d) { int a{}; char c = '#'; stringstream stream; stream << d; stream >> a >> c; if (c != '#') { cerr << "error\n"; return; } cout << a << endl; } int main() { get_int(4.5); // error get_int(8.3); // error get_int(5); // 5 return 0; } Try this:
#include <iostream> #include <сmath> using namespace std; int main() { int i; double d; cin >> d; i = d; if (abs(d - i) > 0.000001) cout << "error" << endl; } 3.0000000000000000000001 :) - ideone.com/E2ZwlD Or, the second option - as the author wanted - 3,2 (see for yourself) ... - HarryLittle modified version of "Kto To":
#include <iostream> #include <string> int main() { using namespace std; int i; double d; string m; getline(cin,m); const char *p = m.c_str(); i = stoi(p); d = atof(p); if (d!=i) cout << "error" << endl; return 0; } Compilation:
g++ -std=c++11 main.cpp Get the string and look for a point in the comments is advised. If there is, then fractional. It seems that this is exactly how the compiler parser works, so the ".8" entry makes sense. You can first replace the comma with a period and then analyze. Or vice versa.
Source: https://ru.stackoverflow.com/questions/826837/
All Articles
3,2decimal? - vp_arth