gpt4 book ai didi

C++ 变量检查

转载 作者:行者123 更新时间:2023-11-28 07:23:41 25 4
gpt4 key购买 nike

假设我希望用户输入一个整数,但他输入了 double 值或字符值,我该如何检查用户是否输入了正确的类型。

string line;
getline(cin, line);
// create stringstream object called lineStream for parsing:
stringstream lineStream(line);
string rname;
double res;
int node1,node2;
lineStream >> rname >> res >> node1 >> node2;

如何检查有效的输入类型?

最佳答案

您检查流是否正常:

if (lineStream >> rname >> res >> node1 >> node2)
{
// all reads worked.
}

你可能想在最后检查垃圾。

if (lineStream >> rname >> res >> node1 >> node2)
{
char x;
if (lineStream >> x)
{
// If you can read one more character there is junk on the end.
// This is probably an error. So in this situation you
// need to do somethings to correct for this.
exit(1);
}

// all reads worked.
// AND there is no junk on the end of the line.
}

评论展开。

来自以下评论:

if i input an integer for rname, it still works. for exmaple:

string line; getline(cin, line);
stringstream lineStream(line); // created stringstream object called lineStream for parsing
string rname;
if (lineStream >> rname) { cout << "works"; }

让我们假设 rname 有一些属性可以让我们将它与数字区分开来。例如:它必须是一个名字。即它必须只包含字母字符。

struct Name
{
std::string value;
friend std::istream& operator>>(std::istream& s, Name& data)
{
// Read a word
s >> data.value;

// Check to make sure that value is only alpha()
if (find_if(data.value.begin(), data.value.end(), [](char c){return !isalpha(c);}) != str.end())
{
// failure is set in the stream.
s.setstate(std::ios::failbit);
}
// return the stream
return s;
}
};

现在你可以读一个名字了。

Name rname; 
if (lineStream >> rname) { cout << "works"; }

如果您为 rname 输入一个整数,这将失败。

拉伸(stretch)答案

如果您有多行相同的信息要阅读。然后值得将它包装在一个类中并定义一个输入流运算符。

strcut Node
{
Name rname;
double res;
int node1;
int node2;

friend std::istream& operator>>(std::istream& s, Node& data)
{
std::string line;
std::getline(s, line);

std::stringstream linestream(line);
lineStream >> data.rname >> data.res >> data.node1 >> data.node2;

if(!linestream)
{
// Read failed.
s.setstate(std::ios::failbit);
}
return s;
}
};

现在可以很容易地阅读循环中的行:

Node n;
while(std::cin >> n)
{
// We read another node successfully
}

关于C++ 变量检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19068717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com