int i = 4;
string text = "Player ";
cout << (text + i);

我想打印参与人4。

上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?


当前回答

这里有一个小的转换/附加示例,其中有一些我以前需要的代码。

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}

输出将是:

/dev/video
/dev/video456
/dev/video321
/dev/video123

请注意,在最后两行中,您在实际打印出修改后的字符串之前保存了它,如果需要,您可以稍后使用它。

其他回答

你也可以尝试用std::string::push_back连接玩家的号码:

代码示例:

int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;

你会在控制台看到:

球员4

我能想到的最简单的方法是: 它将作为单个字符串和字符串数组工作。 我正在考虑一个字符串数组,因为它是复杂的(有点相同将跟随字符串)。 我创建了一个名称数组,并附加了一些整数和字符与它,以显示它是多么容易附加一些int和字符字符串,希望它有帮助。 长度只是用来衡量数组的大小。如果您熟悉编程,那么size_t是一个无符号整型

#include<iostream>
    #include<string>
    using namespace std;
    int main() {

        string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
        int length = sizeof(names) / sizeof(names[0]); //give you size of array
        int id;
        string append[7];    //as length is 7 just for sake of storing and printing output 
        for (size_t i = 0; i < length; i++) {
            id = rand() % 20000 + 2;
            append[i] = names[i] + to_string(id);
        }
        for (size_t i = 0; i < length; i++) {
            cout << append[i] << endl;
        }


}

如果你用cout,你可以直接把整数写进去,就像

std::cout << text << i;

c++将各种对象转换为字符串的方法是通过字符串流。如果手边没有,就自己创建一个。

#include <sstream>

std::ostringstream oss;
oss << text << i;
std::cout << oss.str();

或者,您可以转换整数并将其附加到字符串。

oss << i;
text += oss.str();

最后,Boost库提供Boost::lexical_cast,它使用类似于内置类型强制转换的语法包装stringstream转换。

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

这也适用于其他方式,即解析字符串。

这里的一种方法是直接打印输出,如果你的问题需要它。

cout << text << i;

否则,最安全的方法之一就是使用

sprintf(count, "%d", i);

然后复制它到你的“文本”字符串。

for(k = 0; *(count + k); k++)
{ 
  text += count[k]; 
} 

这样,您就有了所需的输出字符串

有关sprintf的更多信息,请参见: http://www.cplusplus.com/reference/cstdio/sprintf

如果使用Windows/MFC,并且需要字符串的即时输出,请尝试:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);