如何检查输入是否为整数/字符串?

时间:2012-11-18 13:59:06

标签: c++

我的问题是我不知道如何插入一条规则,如果用户在字符串上输入了一个数字,它将cout一个警告说它无效,如果用户输入一个字符串则相同/ char上的成绩。怎么样?我一直在尝试,但公式不起作用。

int x, cstotal = 100, extotal = 150;

double scorecs, exscore, labtotala, labtotalb, total;

string mystr = "";

cout << "Compute for: " << "\n" << "1. Laboratory Grade " << "\n" << "2. Lecture Grade" << "\n" << "3. Exit" << "\n";
cout << "Please enter a number: ";
cin >> x;
switch (x) {
case 1:

    cout << "Compute for laboratory grade." << "\n";
    cout << "Enter Student Name: ";
    cin >> mystr;


    cout << "Good day, " << mystr << " . Please provide the following grades: " << "\n";
    cout << "CS Score: ";
    cin >> scorecs;

    cout << "Exam Score: ";
    cin >> exscore;


    labtotala = scorecs / cstotal * 0.6;
    labtotalb = exscore / extotal * 0.4;
    total = labtotala + labtotalb;
    cout << "Your Laboratory Grade is " << total * 100 << "\n";
    system("pause");
    break;
case 2:
    cout << "Compute for lecture grade." << "\n";
    cout << "Enter Student Name: ";
    cin >> mystr;
    cout << "Good day, " << mystr << " . Please provide the following grades: " << "\n";
    cout << "CS Score: ";
    cin >> scorecs;
    cout << "Exam Score: ";

    cin >> exscore;
    labtotala = scorecs / cstotal * 0.7;
    labtotalb = exscore / extotal * 0.3;
    total = labtotala + labtotalb;
    cout << "Your Lecture Grade is " << total * 100 << "\n";
    system("pause");
    break;

6 个答案:

答案 0 :(得分:10)

cin在输入无效类型时设置failbit

int x;
cin >> x;

if (!cin) {
    // input was not an integer
}

您还可以使用cin.fail()检查输入是否有效:

if (cin.fail()) {
    // input was not valid
}

答案 1 :(得分:4)

这样的事情怎么样:

std::string str;
std::cin >> str;

if (std::find_if(str.begin(), str.end(), std::isdigit) != str.end())
{
    std::cout << "No digits allowed in name\n";
}

上面的代码循环遍历整个字符串,为每个字符调用std::isdigit。如果std::isdigit函数对任何字符都返回true,意味着它是一个数字,那么std::find_if会在找到它的字符串中返回该位置的迭代器。如果未找到任何数字,则返回end迭代器。这样我们就可以看到字符串中是否有任何数字。

C ++ 11标准还引入了可以使用的新algorithm functions,但基本上可以实现上述功能。可以使用的是std::any_of

if (std::any_of(str.begin(), str.end(), std::isdigit))
{
    std::cout << "No digits allowed in name\n";
}

答案 2 :(得分:3)

    cout << "\n Enter number : ";
    cin >> ch;
    while (!cin) {
        cout << "\n ERROR, enter a number" ;
        cin.clear();
        cin.ignore(256,'\n');
        cin >> ch;
    }

答案 3 :(得分:1)

使用流的.fail()方法。如下所示: -

   cin >> aString;

  std::stringstream ss;
  ss << aString;
  int n;
  ss >> n;

  if (!ss.fail()) {
   // int;
  } else {
  // not int;
   }

答案 4 :(得分:0)

您可以使用cin.fail()方法!当cin失败时,它将为true,您可以让while循环循环,直到cintrue

cin>>d;
while(cin.fail()) {
    cout << "Error: Enter an integer number!"<<endl;
    cin.clear();
    cin.ignore(256,'\n');
    cin >> d;
}

答案 5 :(得分:0)

anaemic