0

I am fairly new to programming and have to create a program which reads the prompt: "I have 8 dollars to spend." It then needs to print out with each word on a separate line, and then if any of the strings is numeric, it needs to be divided by 2. Therefore it should end up printing out as:

I
have
4
dollars
to
spend.

I have managed to do everything, except finding the numeric value and dividing it by 2. So far I have this:

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

After looking through various other posts, I cannot manage to get this to work. I'm assuming its an if/else statement within the while loop along the lines of, if numeric, set int num to num / 2 then cout << num << endl;, else cout << word << endl;, but I can't figure it out.

Thanks in advance.

3 Answers 3

2

You can use the stringstream class, which handles conversions between strings and other data types, to attempt to convert a given string to a number. If the attempt is successful, you know The stringstream object allows you to treat a string as though it is a stream similar to cin or cout.

Incorporate this into your while loop, like so:

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;

}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh, thank you so much, that worked. I actually tried something nearly identical to that, except I didn't include stringstream convert(word);. Really appreciate the help.
1

The strtol (C++11 version that works on std::string directly: std::stol) function is really good for testing whether a string holds a number, and if so, what the numeric value is.

Or you could continue using iostreams like you have been... try extracting a number (int or double variable), and if that fails, clear the error bit and read a string.

Comments

0

I dont have 50 rep so I cant comment, thats why I'm writing it as answer. I think you can check it character by character, using Ascii value of each char, & if there are ascii values representing numbers between two spaces(two \n in this case as you've already seperated each word), then you have to divide the number by 2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.