Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Q. The question is to take input like 1,2,3 and print 1(\n)2(\n)3..
iam using stringstream for that but for the last integer it is creating problem for the integer it takes last and first integer together
-> iam aware of other methods also like getline with a delimiter (,) or making a function that replace ',' with '\n'.
-> i want to find mistake in this stringstream program..

What I have tried:

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    char waste;
    int a,b,c;
    string input;
    cin >> input;
    stringstream ss;
    ss << input;
    ss >> a;
    ss << input;
    ss >> waste;
    ss << input;
    ss >> b;
    ss << input;
    ss >> waste;
    ss << input;
    ss >> c;
    cout << a << endl << b << endl << c << endl;   
    return 0;
}

INPUT
1,2,3
OUTPUT
1
2
31(it just took the first character of the input string along with the last character)
EXPECTED OUTPUT
1
2
3
CHANGE
It is working correct if the input is 1,2,3/ instead of 1,2,3
Posted
Updated 3-Nov-22 3:02am

You are reading the complete string text ("1,2,3") into ss each time, not just a single character. Change the code to the following to see what I mean:
C++
char waste;
int a,b,c;
string input;
cin >> input;
stringstream ss;
ss << input;
cout << "ss: " << ss.str() << endl;
ss >> a;
ss << input;
ss >> waste;
cout << "ss: " << ss.str() << endl;
ss << input;
ss >> b;
ss << input;
ss >> waste;
cout << "ss: " << ss.str() << endl;
ss << input;
ss >> c;
cout << a << endl << b << endl << c << endl;
 
Share this answer
 
Comments
Parth Vijay 3-Nov-22 20:19pm    
ok, i got the mistake and got the correct answer..
This
C++
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    // Enter your code here. Read input from STDIN. Print output to STDOUT 
    char waste;
    int a,b,c;
    string input;
    cin >> input;
    stringstream ss(input);
    ss >> a >> waste >> b >> waste >> c;
    cout << a << "\n" << b << "\n" << c << "\n";
    return 0;
}
works for me.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900