Numeric value then print its value doubled

My output isnt printing the same output as my professor. I have everything correct so far except I dont have 7 as and out put, which my professor dose. Am I doing something wrong?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    string name = "Hello world, there are 3.5 items";
    istringstream iss(name);
    
    do{
        string name;
        iss >> name;
        
        cout << "Substring : " << name << endl;
    }while(iss);
}



my ouput below
1
2
3
4
5
6
Hello
world
there
are
3.5
items
Last edited on
What output are you expecting?
@mathnerd,
If your professor outputs 7 items from a sentence with 6 in then he has achieved a minor miracle. Or did you intend to double that 3.5? Your code shows no intention of doing so. I think you had better clarify what you are actually trying to do.

You continue to output (on line 15) even after the stream has failed/finished (on line 13), so, as written, you will get a spurious blank. I should use a while at the top of the loop; something like
while ( iss >> item )

I use item here, because you also create two string variables called name - legitimate (just), but a recipe for confusion.

What you have written as "my ou[t]put" is not actually the output of your posted code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
   string name = "Hello world, there are 3.5 items";
   istringstream iss( name );
   
   string item;
   while ( iss >> item )
   {
      cout << "Substring : " << item << endl;

      // Test if it is numeric (is that what you intended?)
      double number;
      if ( stringstream( item ) >> number ) cout << "Double that number is " << 2 * number << endl;
   }
}


Substring : Hello
Substring : world,
Substring : there
Substring : are
Substring : 3.5
Double that number is 7
Substring : items
Last edited on
Topic archived. No new replies allowed.