繁体   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