我需要能够输入一个句子并将其吐出。但是,如果在句子中输入数字,则应与单词一起输出,但必须加倍。
我试过在我的代码中实现一个 if 语句,看看我是否可以检查是否输入了一个数字,如果可以,在流 *2 中打印出该值,但是这不起作用,因为如果我先输入一个数字然后某些文本会中断,如果我不输入数字作为句子的第二个值,那么它只会打印输入的第一个单词。
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream>
using namespace std;
int main()
{
string sentence;
string word;
float val=0;
cout<<"Enter a sentence: ";
getline(cin, sentence);
stringstream ss;
ss.str(sentence);
while (ss >> word || ss >> val)
{
if (ss >> val)
{
cout << val * 2;
}
else
{
cout << word << endl;
}
}
return 0;
}
如果我输入像“我今天走了 2 次”这样的句子,那么它应该输出为:
I
walked
4
times today
但这只会输出为:
I
解决了这个问题,不得不使用 ss.eof() 方法去到 StreamString 的末尾并停止,如果输入到字符串中的值是一个数字,它将被打印出来。当遇到某个 if 语句时,我的程序停止了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句