Checking if user inputs number or string

Hi all,
This doesn't work, How can I check if the user enters a number instead of
a character?

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
  #include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

void welcome();
bool start();

int main()
{
    welcome();
    start();
    return 0;
}

void welcome(){
    std::cout << "**** Grades Calculation Program ****";
}

bool start()
{
    std::string answer;
    std::cout << "\n\nStart Program (Y/N):  ";
    std::getline(std::cin, answer);
    while((std::cin.fail()))
    {
        std::cin.clear();
        std::cin.ignore();
        std::cout << "Incorrect Input!! (Start Program (Y/N):  ";
        std::cin >> answer;
    }
    if(answer != "Y" || "y"){
        return false;
    }
    return true;
}
> if(answer != "Y" || "y")
Well this should be
if(answer != "Y" || answer == "y")
>This doesn't work
What doesn't work? The loop? The checking to see whether it's an integer or a string? What do you want to work? Your question is a bit vague.

> How can I check if the user enters a number instead of a character?

The quickest example I can give in some code is this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

bool getInput(int& input) {
  std::cin >> input;
  return (!std::cin) ? false : true;
}

int main() {
  int myValue;
  while(!getInput(myValue)) {
    std::cin.clear();
    std::cin.ignore(256, '\n');
    std::cout  << "Value was not of type int!\n";
  }
  return 0;
}
Topic archived. No new replies allowed.