0

我对编程相当陌生,必须创建一个程序来读取提示:“我有 8 美元要花。” 然后它需要将每个单词打印在单独的行上,然后如果任何字符串是数字,则需要除以 2。因此它最终应该打印为:

I
have
4
dollars
to
spend.

除了找到数值并将其除以 2 之外,我已经设法做所有事情。到目前为止,我有这个:

    #include <iostream>
    #include <string>
    #include <sstream>

    using namespace std;

    int main()
    {
string prompt;
string word;

cout << "Prompt: ";

getline(cin, prompt);

stringstream ss;
ss.str(prompt);

while (ss >> word)
{
cout << word << endl;
}

return 0;
}

在浏览了其他各种帖子后,我无法让它发挥作用。我假设它是while循环中的if/else语句,如果是数字,则将int num设置为num / 2然后cout << num << endl;,否则cout << word << endl;,但是我想不通。

提前致谢。

4

3 回答 3

2

您可以使用处理字符串和其他数据类型之间转换的 stringstream 类来尝试将给定字符串转换为数字。如果尝试成功,您就知道 stringstream 对象允许您将字符串视为类似于 cin 或 cout 的流。

将其合并到您的 while 循环中,如下所示:

while (ss >> word)
{
int value = 0;
stringstream convert(word); //create a _stringstream_ from a string
//if *word* (and therefore *convert*) contains a numeric value,
//it can be read into an _int_
if(convert >> value) { //this will be false if the data in *convert* is not numeric
  cout << value / 2 << endl;
}
else
  cout << word << endl;

}
于 2013-08-28T05:27:24.100 回答
1

( strtolC++11 版本std::string直接运行: std::stol) 函数非常适合测试字符串是否包含数字,如果是,那么数值是什么。

或者您可以像以前一样继续使用 iostreams……尝试提取一个数字(intdouble变量),如果失败,清除错误位并读取一个字符串。

于 2013-08-28T05:18:39.153 回答
0

我没有 50 个代表,所以我无法发表评论,这就是我将其写为答案的原因。我认为你可以逐个字符地检查它,使用每个字符的 Ascii 值,如果有 ascii 值表示两个空格之间的数字(在这种情况下是两个 \n,因为你已经分隔了每个单词),那么你必须除以数字加 2。

于 2013-08-28T05:20:16.403 回答