C++ if(cin>>input) 在 while 循环中无法正常工作



我是 c++ 的新手,我正在尝试解决 Bjarne Stroustrups 书"编程原理和使用C++练习"第 4 章中的练习 6,但不明白为什么我的代码不起作用。

练习:

制作一个包含十个字符串值"零"、"一"、...的向量, "九"。在将数字转换为其 相应的拼写值:例如,输入 7 给出输出 七。具有相同的程序,使用相同的输入循环,转换 将数字拼成数字形式;例如,输入 7 给出 输出 7.

我的循环只对字符串执行一次,对 int 执行一次,循环似乎还在继续,但我给出哪个输入并不重要,它没有做它应该做的事情。

有一次它适用于多个 int 输入,但每隔一次。这真的很奇怪,我不知道如何以不同的方式解决这个问题。

如果有人能帮助我,那就太棒了。 (我也不是母语人士,很抱歉,如果有一些错误)

这段代码中的库是随书提供的库,我想是为了让我们菜鸟更容易开始。

#include "std_lib_facilities.h"
int main()
{
vector<string>s = {"zero","one","two","three","four","five","six","seven","eight","nine"};
string input_string;
int input_int;
while(true)
{
if(cin>>input_string)
{
for(int i = 0; i<s.size(); i++)
{
if(input_string == s[i])
{
cout<<input_string<<" = "<<i<<"n";
}
}
}
if(cin>>input_int)
{
cout<<input_int<<" = "<<s[input_int]<<"n";
}
}
return 0;
}

当您(成功)从std::cin读取输入时,输入将从缓冲区中提取。缓冲区中的输入将被删除,无法再次读取。

当您第一次作为字符串读取时,也会将任何可能的整数输入读取为字符串。

有两种方法可以解决此问题:

  1. 尝试先 阅读int。如果失败,请清除错误并读取为字符串。

  2. 读取为字符串,并尝试转换为int。如果转换失败,则有一个字符串。

if(cin >> input)在 while 循环中无法正常工作?

程序输入的可能实现如下所示:

std::string sentinel = "|";
std::string input;
// read whole line, then check if exit command
while (getline(std::cin, input) && input != sentinel)
{
// use string stream to check whether input digit or string
std::stringstream ss(input);
// if string, convert to digit
// else if digit, convert to string
// else clause containing a check for invalid input
}

例如,要区分intstring值,您可以使用 peek()。 最好转换的最后两个动作(在intstring之间)由单独的函数完成。

假设包含标头:

#include <iostream> 
#include <sstream> 

最新更新