Three Integers into 1 string with spacebars;

2019-09-22 07:00发布

I have input like this:

1581 303 1127 Bravo

I want to put it into strings like this:

string a="1581 303 1127";
string b="Bravo";

How can i do that?

标签: c++ string int
5条回答
贪生不怕死
2楼-- · 2019-09-22 07:11

You can do something like this:

getline(cin, a); // read the numbers followed by a space after each number and press enter 

getline(cin, b); // read the string 

cout << a << endl << b; // output the string with numbers

// first then the string with the word 'Bravo'
查看更多
一夜七次
3楼-- · 2019-09-22 07:11

A way in standard C++ that doesn't rely on reading the values is

#include <string>
#include <sstream>

int main()
{
    int i1 = 1581;
    int i2 = 303;
    int i3 = 1127;

    std::ostringstream ostr;
    ostr << i1 << ' ' << i2 << ' ' << i3 << ' ' << "Bravo";

     // possible to stream anything we want to the string stream

    std::string our_string = ostr.str();    // get our string

    std::cout << our_string << '\n';     // print it out

}
查看更多
做个烂人
4楼-- · 2019-09-22 07:21

a simpel c++ style approach would be using std::to_string

string += " "
string += std::to_string(int_value);

this adds an " int" value at the end of your string.

But have you consider using string streams instead?

#include <sstream>

std::stringstream sstream;
sstream << int_1 << " " << int_2 << std::endl;

and if you wish convert it to an good old string:

string = sstream.str();
查看更多
太酷不给撩
5楼-- · 2019-09-22 07:25

Just read them as strings and put them together.

std::string x1, x2, x3;
std::cin >> x1 >> x2 >> x3;
std::string a = x1 + " " + x2 + " " + x3;
std::string b;
std::cin >> b;
查看更多
一纸荒年 Trace。
6楼-- · 2019-09-22 07:27

Based on the fact that you take first three as int and last as string do it like this.

int i1, i2, i3; //Take input in three integers sprintf(a, "%d %d %d", i1, i2, i3);

查看更多
登录 后发表回答