Search code examples
c++iostringstream

If an integer is entered into the StringStream, double it and print it


I need to be able to enter a sentence and have it spit back out. However, if a number is entered in the sentence, it should be output along with the words but it must be doubled.

I've tried implementing an if statement into my code to see if I could check if a number was entered, and if so print out that value in the stream *2, however this doesn't work because if I enter a number first then some text it breaks, if I don't enter the number as the second value of the sentence than it only prints the first word entered.

#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;
}

If I enter a sentence like "I walked 2 times today" then it should output it as:

I 
walked
4 
times today

But this would only be output as:

I

Solution

  • Solved the issue, had to use ss.eof() method to go to the end of the StreamString and stop and if a value that was entered into the string was a number, it would be printed out. My program was stopping when a certain if statement was met.