用空格键将三个整数合并为 1 个字符串;

Three Integers into 1 string with spacebars;

我有这样的输入:

1581 303 1127 Bravo

我想把它变成这样的字符串:

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

我该怎么做?

基于您将前三个作为 int,最后一个作为字符串的事实,请这样做。

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

只需将它们作为字符串读取并将它们放在一起即可。

std::string x1, x2, x3;
std::cin >> x1 >> x2 >> x3;
std::string a = x1 + " " + x2 + " " + x3;
std::string b;
std::cin >> b;

一个 simpel c++ 风格的方法将使用 std::to_string

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

这会在您的字符串末尾添加一个“int”值。

但是您考虑过使用字符串流吗?

#include <sstream>

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

如果你想把它转换成一个好的旧字符串:

string = sstream.str();

你可以这样做:

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'

标准 C++ 中不依赖于读取值的方法是

#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

}