input string stream question . please help

2 #include <string>
3 #include <sstream>
4
5 using namespace std;
6
7 int main()
8 {
9 string piece1, piece2, word, secondword, secondlastword;
10 int wordcount1 = 0, wordcount2 = 0, count1 = 0, count2= 0;
11
12 getline(cin, piece1);
13 getline(cin, piece2);
14
15 istringstream p1 (piece1);
16 istringstream p2 (piece2);
17
18 while (p1 >> word)
19 wordcount1++;
20 while (p2 >> word)
21 wordcount2++;
22
23
24 while (p1 >> word)
25 {
26 count1++;
27 if (count1 == 2)
28 secondword = word;
29 }
30 while (p2 >> word)
31 {
32 count2++;
33 if (count2 == (wordcount2 - 1))
34 secondlastword = word;
35 }
36
37 cout << secondword << " " << secondlastword;
38
39
40
41
42 return 0;
43 }



my objective for this piece of code is to read in 2 lines i.e

My name is John Smith.
I live in Boston, Massachusetts

and get the second word of the first line "name" and the second last word of the second line "Boston," and then print them out as

name Boston,

question 1 :
is there some syntax issue in the while loops from 24 to 29 and 30 to 35 because i get nothing printed. so string secondword and secondlastword are both empty.
question 2 :
any better way of accomplishing the objective besides the method above.

thanks. your help is much appreciated.
Last edited on
Your problem is that in lines 18 and 20, you are emptying the stringstream.

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <string>
#include <sstream>

using namespace std;

int main()
{
  string piece1, piece2, word, secondword, secondlastword;
  int count1 = 0;
  
  getline(cin, piece1);
  getline(cin, piece2);
  
  istringstream p1 (piece1);
  istringstream p2 (piece2);
  
  while (p1 >> word)
  {
    count1++;
    if (count1 == 2)
      secondword = word;
  }
  
  while (p2 >> word)
  {
    if ( p2.eof() )
      secondlastword = word;
  }
  cout << secondword << " " << secondlastword;
  return 0;
}
Last edited on
doesn't work i cant seem to be able to get the second last word of the second line. i changed my code so i could get the second word of the first line as follows though.

#include <iostream>
2 #include <string>
3 #include <sstream>
4
5 using namespace std;
6
7 int main()
8 {
9
10 string piece1, piece2, word, secondword, secondlastword;
11 int wordcount1 = 0, wordcount2 = 0, count2= 0;
12
13 getline(cin, piece1);
14 getline(cin, piece2);
15
16
17 istringstream p1 (piece1);
18 istringstream p2 (piece2);
19
20 while (p1 >> word)
21 {
22 wordcount1++;
23 if (wordcount1 == 1)
24 {
25 p1 >> secondword;
26 wordcount1++;
27 }
28 }

Topic archived. No new replies allowed.