C ++中的连接运算符? [英] Concatenation operator in C++?
问题描述
我有一个应用程序,我需要在一个变量中组合字符串,如:
int int_arr [4]
int_arr [1] = 123;
int_arr [2] = 456;
int_arr [3] = 789;
int_arr [4] = 10;
std :: string _string =Text+ int_arr [1] +Text+ int_arr [2] +Text+ int_arr [3] +Text+ int_arr [4]
它给我的编译错误
错误C2210:'+'操作符不能在表达式的第二个字符串上添加指针。
至于我可以告诉我组合字符串字面量和整数,而不是指针。
有没有另一个连接运算符,我应该使用?
我使用Visual Studio 2010
您可以在 Java 中执行此操作,因为它使用 toString()
每个部分。
如果你想在C ++中使用相同的方式,你必须显式转换这些整数到字符串,以使这个工作。 p>
如下:
#include< iostream>
#include< sstream>
std :: string intToStr(int i){
std :: ostringstream s;
s<<一世;
return s.str();
}
int main(void){
int var = 7;
std :: string s =Var is'+ intToStr(var)+';
std :: cout<< s<< std :: endl;
return 0;
}
当然,您可以使用:
std :: ostringstream os;
os<< Var is'< var< ';
std :: string s = os.str();
这很容易。
I have an application in which I need to combine strings within a variable like so:
int int_arr[4];
int_arr[1] = 123;
int_arr[2] = 456;
int_arr[3] = 789;
int_arr[4] = 10;
std::string _string = "Text " + int_arr[1] + " Text " + int_arr[2] + " Text " + int_arr[3] + " Text " + int_arr[4];
It gives me the compile error
Error C2210: '+' Operator cannot add pointers" on the second string of the expression.
As far as I can tell I am combining string literals and integers, not pointers.
Is there another concatenation operator that I should be using? Or is the expression just completely wrong and should figure out another way to implement this?
BTW I am using Visual Studio 2010
You can do this in Java since it uses the toString()
method automatically on each part.
If you want to do it the same way in C++, you'll have to explicitly convert those integer to strings in order for this to work.
Something like:
#include <iostream>
#include <sstream>
std::string intToStr (int i) {
std::ostringstream s;
s << i;
return s.str();
}
int main (void) {
int var = 7;
std::string s = "Var is '" + intToStr(var) + "'";
std::cout << s << std::endl;
return 0;
}
Of course, you can just use:
std::ostringstream os;
os << "Var is '" << var << "'";
std::string s = os.str();
which is a lot easier.
这篇关于C ++中的连接运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!