gpt4 book ai didi

C++ stringstream,如果word是数字,除以二

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

我是编程新手,必须创建一个程序来读取提示:“我有 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;,但是我想不通。

提前致谢。

最佳答案

您可以使用 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;

}

关于C++ stringstream,如果word是数字,除以二,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18479905/

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