![](/img/trans.png)
[英]How to read an input from a file one at a time similar to reading input from console using cin/scanf in c++?
[英]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'
的字符代碼為48
到57
。 因此,如果您簡單地從字符代碼中減去48
(這是'0'
的字符代碼),您將得到介於0
和9
之間的結果,這是數字的值。
這是一個示例程序:
#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.