【问题标题】:C++ stringstream, if word is numeric, divide by twoC ++ stringstream,如果单词是数字,则除以二
【发布时间】:2013-08-31 01:18:43
【问题描述】:

我对编程很陌生,必须创建一个程序来读取提示:“我有 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

提前致谢。

【问题讨论】:

    标签: c++ stringstream


    【解决方案1】:

    strtol(直接在std::string上工作的C++11版本:std::stol)函数非常适合测试字符串是否包含数字,如果是,那么数值是什么。

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        您可以使用处理字符串与其他数据类型之间转换的 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;
        
        }
        

        【讨论】:

        • 啊,非常感谢,这很有效。我实际上尝试了几乎相同的东西,除了我没有包含 stringstream convert(word);。非常感谢您的帮助。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-24
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多