C++ 如何检查输入是否是没有任何其他字符的有效整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20287186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if the input is a valid integer without any other chars?
提问by user2699298
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int x;
cout << "5 + 4 = ";
while(!(cin >> x)){
cout << "Error, please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (x == (5 + 4)){
cout << "Correct!" << endl;
}
else{
cout << "Wrong!" << endl;
}
return 0;
}
How can I check if the user inputs a valid integer? In this program I wrote above, if the user inputs 9, it should be correct, however, if the user inputs 9afor example, it should return an error, but it doesn't for some reason. How can I correct it?
如何检查用户输入的整数是否有效?在我上面写的这个程序中,如果用户输入9,它应该是正确的,但是,如果用户输入9a例如,它应该返回一个错误,但由于某种原因它不会。我该如何纠正?
How I did it using cin.peek()
我是如何使用 cin.peek() 做到的
#include <iostream>
#include <limits>
#include <stdio.h>
using namespace std;
int main()
{
int x;
bool ok;
cout << "5 + 4 = ";
cin >> x;
while(!ok){
cin >> x;
if(!cin.fail() && (cin.peek() == EOF || cin.peek() == '\n')){
ok = true;
}
else{
cout << "Error, please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
if (x == (5 + 4)){
cout << "Correct!" << endl;
}
else{
cout << "Wrong!" << endl;
}
return 0;
}
回答by Angew is no longer proud of SO
You could read a string, extract an integer from it and then make sure there's nothing left:
您可以读取一个字符串,从中提取一个整数,然后确保没有任何剩余:
std::string line;
std::cin >> line;
std::istringstream s(line);
int x;
if (!(s >> x)) {
// Error, not a number
}
char c;
if (s >> c) {
// Error, there was something past the number
}
回答by Constantin
bool isIntegerNumber(const std::string& string){
std::string::const_iterator it = string.begin();
int minSize = 0;
if(string.size()>0 && (string[0] == '-' || string[0] == '+')){
it++;
minSize++;
}
while (it != string.end() && std::isdigit(*it)) ++it;
return string.size()>minSize && it == string.end();
}
回答by James Kanze
You have a line oriented input, so you should probably be using
getline. Something like:
您有一个面向行的输入,因此您可能应该使用
getline. 就像是:
bool
getIntFromLine( std::istream& source, int& results )
{
std::string line;
std::getline( source, line );
std::istringstream parse( source ? line : "" );
return parse >> results >> std::ws && parse.get() == EOF;
}
should do the trick.
应该做的伎俩。
Using this, your loop would be:
使用这个,你的循环将是:
while ( !getIntFromLine( std::istream, x ) ) {
std::cout << "Error, please try again." << std::endl;
}
Note that this technique also means that you don't have to worry about clearing the error or resynchronizing the input.
请注意,此技术还意味着您不必担心清除错误或重新同步输入。
回答by James Kanze
For the reason this happens, take a look at this link:
由于发生这种情况的原因,请查看此链接:
Extracts and parses characters sequentially from the stream to interpret them as the representation of a value of the proper type, which is stored as the value of val. Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to false). Then (if good), it calls num_get::get (using the stream's selected locale) to perform both the extraction and the parsing operations, adjusting the stream's internal state flags accordingly. Finally, it destroys the sentry object before returning.
从流中按顺序提取和解析字符以将它们解释为正确类型的值的表示,该值存储为 val 的值。在内部,该函数通过首先构造哨兵对象(将 noskipws 设置为 false)来访问输入序列。然后(如果好),它调用 num_get::get(使用流的选定区域设置)来执行提取和解析操作,相应地调整流的内部状态标志。最后,它在返回之前销毁哨兵对象。
Then observe the behavior if you attempt something like this:
如果你尝试这样的事情,然后观察行为:
int x = 0;
cin >> x;
std::cout << x << std::endl;
std::cout << cin.good() << std::endl;
g++-4.8 -std=c++11 -O3 -Wall -pedantic -pthread main.cpp && echo "900a100" | ./a.out
// Output:
// 900
// 1
If you input "a100" instead, it outputs:
如果您输入“a100”,它会输出:
0
0
回答by bgs
try this:
尝试这个:
std::string input;
std::cin >> input;
if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
//input is integer
}
Refer this :
参考这个:
回答by RichardPlunkett
One I have seen that works for some situations is:
我见过一种适用于某些情况的方法是:
- Read the input as string.
cin >> str - Decode to number: atoi, or sscanf, or stringstream, etc.
- print the number into a string (using sprintf or stringstream)
- check if its equal to read string. (using strings ==, not char*)
- 将输入读取为字符串。
cin >> str - 解码为数字:atoi,或sscanf,或stringstream等。
- 将数字打印成字符串(使用 sprintf 或 stringstream)
- 检查它是否等于读取字符串。(使用字符串 ==,而不是字符 *)
Quick and simple to do. Uses the Cin>>str word breaking rules, accept negative numbers, rejects overflowing numbers. But it does reject "+10", which in somesituations you are happy wiht, and in some you are not.
做起来又快又简单。使用 Cin>>str 分词规则,接受负数,拒绝溢出数。但它确实拒绝“+10”,在某些情况下您很高兴,而在某些情况下您则不高兴。
回答by Zac Howland
If you can use C++11 (and your compiler has full regex support), you can also use the <regex>library:
如果您可以使用 C++11(并且您的编译器具有完整的正则表达式支持),您还可以使用该<regex>库:
#include <iostream>
#include <limits>
#include <regex>
#include <string>
#include <utility>
int main()
{
std::string line;
std::pair<int, bool> value = std::make_pair(0, false);
std::cout << "5 + 4 = ";
while (!value.second)
{
while (!std::getline(std::cin, line))
{
std::cout << "Error, please try again." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if (!std::regex_match(line, std::regex("(\+|-)?[[:digit:]]+")))
{
std::cout << "Error, please try again." << std::endl;
}
else
{
value = std::make_pair(std::stol(line), true);
}
}
if (value.first == (5 + 4))
{
std::cout << "Correct!" << std::endl;
}
else
{
std::cout << "Incorrect!" << std::endl;
}
return 0;
}

