簡體   English   中英

c++ 可以像 scanf 一樣使用 cin 讀取一個數字嗎

[英]can c++ using cin to read one digit like scanf

c++ 是否具有類似scanf("%1d)的類似度量,在cin >>

或僅#include <cstdin>並使用scanf

我嘗試使用 setw() 但它似乎在字符串中使用

下面,看看這個方法

#include <iostream>

int main(){

    std::cout << "Enter a number : ";
    std::string input;
    std::getline(std::cin, input);

    int num = input[0] - 48; // converting char to int by ASCII values
    // int num = input[0] - '0';  can also be used
    cout << num;
    
    return 0;
}

即使輸入了很多數字,程序也只接受第一個數字。

一個數字就是一個字符。

為了從std::cin讀取單個字符,您可以使用operator>> ,或者您可以使用std::istream::get

使用operator>>

char digit;
std::cin >> digit;

使用std::istream::get

char digit;
std::cin.get( &digit );

為了將char digit轉換為 integer,假設digit'0''9'范圍內,您可以編寫以下內容:

int number = digit - '0';

您可以這樣做,因為 ISO C++ 標准保證字符'0''9'在字符集中連續存儲。 例如,在ASCII中,字符'0''9'的字符代碼為4857 因此,如果您簡單地從字符代碼中減去48 (這是'0'的字符代碼),您將得到介於09之間的結果,這是數字的值。

這是一個示例程序:

#include <iostream>
#include <cstdlib>

int main()
{
    int number;
    char digit;

    //prompt user for input
    std::cout << "Please enter a digit: ";

    //attempt to read a single character
    std::cin >> digit;

    //verify that no input error occurred
    if ( !std::cin )
    {
        printf( "Input error!\n" );
        std::exit( EXIT_FAILURE );
    }

    //verify that character is in the range '0' to '9'
    if ( ! ( '0' <= digit && digit <= '9' ) )
    {
        printf( "Character is not a digit!\n" );
        std::exit( EXIT_FAILURE );
    }

    //convert digit to integer
    number = digit - '0';

    //print result
    std::cout <<
        "The digit was successfully converted to " << number << ".\n";
}

該程序具有以下行為:

Please enter a digit: 7
The digit was successfully converted to 7.

它只接受數字:

Please enter a digit: a
Character is not a digit!

它只會讀取第一個數字,而不是整數:

Please enter a digit: 38
The digit was successfully converted to 3.

暫無
暫無

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

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