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)

  • We'll have to get the data as a string and analyze it - vp_arth
  • In which locale do you have 3,2 decimal? - vp_arth
  • What if the user enters a string? - TigerTV.ru

4 answers 4

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; } 
    • one
      Well, the option is to enter 3.0000000000000000000001 :) - ideone.com/E2ZwlD Or, the second option - as the author wanted - 3,2 (see for yourself) ... - Harry
    • one
      Again - after your correction: ideone.com/hFuhc1 You see, the author gave a fuzzy TK. With this TK result - HZ ... - Harry
    • yes, incorrect input will not help - Kto To
    • does not work (( - user262343
    • @ leocoolguy0: Try to enter 3.2 - TigerTV.ru

    Little 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.