如何在 C++ 中检查符号

P. *_*rov 2 c++ if-statement

我是编程初学者(特别是 C++)。我试图检查传入的字母符号。我只需要“捕捉”从 0 到 9 的数字。所以,我尝试使用它:

// Checking "a". If "a" is a letter, the error must be printed;
if (a!='%d') {
    cout << "pfff! U cant use letters!" << endl;
    return -1;
}
// The end of checking;
Run Code Online (Sandbox Code Playgroud)

但它不起作用。我想我不能在 C++ 中使用 '%d'。我怎么说:“如果有非数字,请检查所有符号并停止程序。”

PS对不起我的英语。我希望你得到我。

The*_*ght 5

是的,isdigit()在这里效果很好。

一个例子是:

    #inlude <iostream>
    #include <ctype.h>
    // in ctype.h is located the isdigit() function
    using namespace std;
    //...
    char test;
    int x;
    cin >> test;
    if ( isdigit(test) )//tests wether test is == to '0', '1', '2' ...
    {
          cin>>putback(test);//puts test back to the stream
          cin >> x;
    }
    else
         errorMsg();
Run Code Online (Sandbox Code Playgroud)

  • 为什么你不在 `cin.get(test);` 中也使用 `operator&gt;&gt;`,即 `cin&gt;&gt;text;`? (2认同)