help please!

sorry I just can't figure this out.
I want to output an error message whenever I input letters and numbers with letters.
please help! thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
  int x;
  
  cout<<"Enter a number:";
  cin>>x;
  
  if(x<0)
  {
    cout<<"negative number";
  }
  else if(x>0)
  {
   cout<<"positive number";
  }
  else if(x==0)
  {
   cout<<"the number is zero";
  }
  else
  {
   cout<<"ERROR-numbers only!";
  }
getch();
}
You can use bool cin.fail() to check if cin >> x was successfull (it won't be for non-integers, since x is int).
Look up cin.clear and cin.ignore functions, as these will come in handy when dealing with looped cin statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
int main()
{
  int x;
  
  cout<<"Enter a number:";
  cin>>x;
  // You can use
  while (cin.fail())
  {
    cin.clear();
    cin.ignore();
    cout<<" No. Enter a NUMBER! :";
    cin>>x;
  }
  /* Or:
  for (int i = 0; cin.fail(); i++)
  {
    cin.clear();
    cin.ignore();
    cout << " No. Enter a NU";
    for (int j = 0; j < i; j++) {  cout << 'U'; }
    cout << "MBER! :"
    cin>>x;
  }
  */  
  if(x<0)
  {
    cout<<"negative number";
  }
  else if(x>0)
  {
   cout<<"positive number";
  }
  else if(x==0)
  {
   cout<<"the number is zero";
  }
  else
  {
   cout<<"ERROR-numbers only!";
  }
getch();
}
thankyou so much JockX. really needed it!
the problem now is, whenever I input, for example two letters, it will output
"No. Enter a NU" two times. is it possible for it to be just one? anyway it solved what I wanted. thanks again!
You can use ignore with parameters specifying how many character to ignore or at which particular character to stop ignoring:
- std::numeric_limits<std::streamsize>::max() - is formal way of saying "As much as it fits inside cin buffer"
- '\n' - is read as: "or when encounter newline" - which happens after pressing Enter.
In full, the line looks like:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Last edited on
thankyou again! very much appreciated.
Topic archived. No new replies allowed.