检查以确保argv [1]是一个整数c ++ [英] Checking to make sure argv[1] is an integer c++
本文介绍了检查以确保argv [1]是一个整数c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于我的程序,我必须确保用户只输入一个正整数。例如如果用户输入12hi它不应该运行程序和打印到std错误。我不太确定如何实现这个。
For my program I have to make sure the user only inputs a positive INTEGER. for example if the user inputted 12hi it should not run the program and print to std error. I am not quite sure how to implement this.
int main(int argc, char *argv[])
{
if(atoi(argv[1]) < 1)
{
cerr << "ERROR!"<< endl;
return 1;
}
return 0;
}
推荐答案
href =http://en.cppreference.com/w/cpp/io/basic_istringstream =nofollow> std :: istringstream
并确保所有数据均已处理:
Pass it to a std::istringstream
and ensure all data was processed:
if (a_argc > 1)
{
std::istringstream in(a_argv[1]);
int i;
if (in >> i && in.eof())
{
std::cout << "Valid integer\n";
}
}
查看在线演示 http://ideone.com/8bEYJq 。
这篇关于检查以确保argv [1]是一个整数c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文