当我在学校学习 C++ 时,这不是一个家庭作业的问题,只是我遇到的一个奇怪问题,我想知道如何解决自己和 future 的引用。
搜索我没有看到任何似乎与此直接相关的内容。
所以我正在寻找 int 类型的输入,但是我在运行程序时注意到,如果收到一个 char 输入(不确定字符串),它会被转换为 int(我在我的教科书中读到这是正常的C++ 行为)。
我的问题是:我如何测试输入的 char 类型,因为它会自动转换为 int?我习惯了 Python、Ruby、PHP 等,通常有一些标准的库方法,但在这里和谷歌搜索似乎没有。下面是我发现这个问题时使用的精简版。
我也想知道:C++ 从什么获取 char 的值?它是 ASCII 值还是其他什么?如果您运行下面的代码并输入任何单个字母字符,您就会明白我在说什么。
我见过一些包含外部库的解决方案,但希望 C++ 的标准库/发行版中有一些东西可以解决这个问题。
如果这是相关的:我的系统是 OS X 10.8 并且正在运行 gcc。
谢谢!
#include<iostream>
using namespace std;
int main()
{
int user_input;
int n;
cout << "Enter a number: ";
cin >> user_input;
for (n = 0; n < user_input; n++)
{
cout << n << endl;
}
cout << user_input << endl;
return 0;
}
最佳答案
how do I test for type char on input
有几种机制可供使用。您可能会考虑以下 2 个:
样式一。
'c' 风格将使用 isdigit() 检查每个输入字符。
即,将用户输入读入字符串,检查每个字符是否为数字等。
std::cout << "Enter a number: ";
std::string user_input;
std::cin >> user_input;
for (int i=0; i<user_int.size(); i++
if (!isdigit(user_input[i])
throw "not a digit";
// if you get here, all the chars in user_input are digits,
// I suppose you might use atoi() to convert, but see next.
注意 - 还有一个十六进制检查,isxdigit()。如果你想允许用户输入逗号或空格字符,你可以对每个你希望允许用户使用的字符使用 user_input.erase(...),但忽略作为数字的一部分。
样式 2。
您可能更喜欢 c++ 风格,我发现它更简单,但需要熟悉 C++ std::string 方法。
std::cout << "Enter a number: ";
std::string user_input;
std::cin >> user_input;
const char* DIGITS = "0123456789";
size_t notaDigit = user_input.find_first_not_of(DIGITS);
if(notaDigit != std::string::npos)
throw "non-digit char found in user_input";
// if you get here, all chars are digits, so convert to integer.
// these days, I would do this in 4 steps.
int user_int = 0;
{
std::stringstream ss;
ss << user_input; // put char string into ss
ss >> user_int; // extract and convert to integer
} // discard and cleanup the stringstream at scope end
std::cout << "user_int: " << user_int << std::endl;
if a char input is received (not sure about string) that it is converted to int
仅供引用 - 我无法在 ubuntu 12.04 上的 gcc 4.8.1 上重现此内容。
通过 std::cin 的字符输入不会转换为 int。
转换尝试在第一个非数字字符处停止将数字转换为整数的一部分。因此,33Y 将转换为 33,因为它在 Y 处停止转换。 ABC 输入(或 AB 输入或 A 输入)将在第一个(非数字)字符处停止转换,因此转换报告为 0。
我相信某些转换尝试(从字符串到 POD)也可以在 istream 上设置标志,但没有检查。
例子:
dmoen@C5:~/cvs-tools/lmbm/src_ut$ ./dmy24
Enter a number: 12
0
1
2
3
4
5
6
7
8
9
10
11
12
dmoen@DOMA5:~/cvs-tools/lmbm/src_ut$ ./dmy24
Enter a number: a
0
dmoen@DOMA5:~/cvs-tools/lmbm/src_ut$ ./dmy24
Enter a number: bcd
0
dmoen@DOMA5:~/cvs-tools/lmbm/src_ut$ ./dmy24
Enter a number: ABC
0
请注意,大多数 C 风格函数会自动将 char 提升为 int。例如,isdigit() 的输入被声明为 int,因此提升使其更易于使用。
C++ 也支持这种提升,但我猜你看到的不是这个。
关于c++ - 当 cin 需要 int 时检测 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21653854/