簡體   English   中英

如何在C ++中檢查符號

[英]How to check symbols in C++

我是編程初學者(特別是在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;

但它不起作用。 我想我不能在C ++中使用'%d'。 我怎么說:“如果有非數字,檢查所有符號並停止程序。”

PS抱歉我的英文。 我希望你能幫助我。

是的, 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();

只需使用isdigit

if (!isdigit(a)) {
    cout << "pfff! U cant use letters!" << endl;
    return -1;
}

你的cout的文字表明你正在尋找isalpha

if (isalpha(a)) {
    cout << "pfff! U cant use letters!" << endl;
    return -1;
}

您可以使用繼承的C庫中的函數isdigit() 這出現在頭文件cctype中 您要求的算法的邏輯是運行輸入的字符串,並在字符不是數字時作出反應。

這是一個示例源代碼:

#include <iostream>
#include <cctype>
#include <utility>
#include <string>
#include <cstdlib>

int main()
{
    int toret = EXIT_SUCCESS;
    std::string str;

    std::getline( std::cin, str );

    for(unsigned int i = 0; i < str.length(); ++i) {
        if ( !std::isdigit( str[ i ] ) ) {
            std::cerr << "Only digits allowed" << std::endl;
            toret = EXIT_FAILURE;
            break;
        }
    }

    return toret;
}

希望這可以幫助。

你必須使用函數isdigit

if (!isdigit(a)) {
    cout << "pfff! U cant use letters!" << endl;
    return -1;
}

你也可以做的就是做你的代碼的反面。 要檢查輸入是否等於或大於0並且例如小於10。

如果是這種情況,它是一個從0到9的數字,如果不是那么輸入是錯誤的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM