Basic problem with my Else statement

I am new to C++ and creating programs to make myself familiar with the basic's but i cant seem to figure out what to put in it.

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

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

int main()

{
int a;
int b;
    cout << " Enter two numbers " ;
    cin>>a;
    cin>>b;

    if (a>b)
    {
    cout<<"The number "<<a<<" is larger than "<<b<<endl;
    }
    else if (a<b)
    {
    cout <<"The number "<<a<<" is smaller than "<<b<<endl;
    }
    else if (a==b)
    {
        cout <<"The number "<<a<<" is the same as "<<b<<endl;
    }
  else();
{
    cout<<"You didn't enter a number"<<endl;
}
system("PAUSE");
    return 0;

}
The else statement has no any condition. Moreover if you checked a < b and a > b then it is obvious that there is only one variant a == b. So you can rewritte your if-else statements the following way

1
2
3
4
5
6
7
8
9
10
11
12
    if (a>b)
    {
    cout<<"The number "<<a<<" is larger than "<<b<<endl;
    }
    else if (a<b)
    {
    cout <<"The number "<<a<<" is smaller than "<<b<<endl;
    }
    else
    {
        cout <<"The number "<<a<<" is the same as "<<b<<endl;
    }
Yeah but what i want is just more control on what happens i guess, like say they enter an "H" i want it to say they entered a LETTER or tell them "H is not a number"
In this case you should check the input not to do comparing values of the variable.
I am rather new to c ++. What do you mean by that? I want it to compare the integer values of a and b but if its a letter or something of the sort, tell them its invalid.
You should check the state of the stream after each operation.
how do i do that?
This is a small example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int num = 0;

int main()
{
  while(num < 1)
  {
    std::cout << "Enter a positive integer: ";
    std::cin >> num;
    if(!std::cin.good())
    {
      num = 0;
      std::cout << char(num) << " is not a positive integer.  Please try again." << std::endl;
      std::cin.clear();
      std::cin.sync();
    }
  }
  return 0;
}
Last edited on
ah oh i get it. wonderful thank you!!
Topic archived. No new replies allowed.