I forgot how to use the sstream library.The goal is to change the int type value in the array to the string type, and to include a comma and a space between the numbers.

Asked 2 years ago, Updated 2 years ago, 30 views

The goal this time is to take out the values in the int-type array and put them in the string type variable by putting a comma and a space between each numeric value.However, in the following program, only one goes into output.I tried, except for spaces, but I only put commas between each number.As a result, 1,4,7,10,13 went into output, but this is not something I really want to do.I want to put a space behind the comma.If anyone knows the solution to this, please take care of it.

#include<iostream>
# include <sstream>

using namespace std;
constint SIZE=5;
int main() {
    int array [SIZE] = {1,4,7,10,13};
    string output;
    US>stringstream s;

    for (inti=0;i<SIZE;i++)
    {
        ss<<array[i]<<", ";
    }
    
    ss>>output;

    cout<<"The result should be 1,4,7,10,13 Not like this: 1,4,7,10,13"<endl;
    cout<<"The result is"<<output<<endl;
    return 0;
}

c++

2022-09-30 11:16

1 Answers

With ss>output, you can only take it out to the front of the space, so use ss.str() to take it out together.
Also, if things go on like this, extra , will be added to the end, so I'm putting a little effort into it.

#include<iostream>
# include <sstream>

using namespace std;
constint SIZE=5;
int main() {
    int array [SIZE] = {1,4,7,10,13};
    string output;
    US>stringstream s;

    for (inti=0;i<SIZE;i++)
    {
        if(i>0)
            ss<<", ";
        ss<<array[i];
    }

    output =ss.str();

    cout<<"The result should be 1,4,7,10,13 Not like this: 1,4,7,10,13"<endl;
    cout<<"The result is"<<output<<endl;
    return 0;
}


2022-09-30 11:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.