字符串连接++问题

问题描述:

大家我有一个字符串连接问题在C++中,这里是我的代码字符串连接++问题

map<double, string> fracs; 
for(int d=1; d<=N; d++) 
    for(int n=0; n<=d; n++)    
     if(gcd(n, d)==1){ 
      string s = n+"/"+d;// this does not work in C++ but works in Java 
      fracs.insert(make_pair((double)(n/d), s)); 
      } 

如何解决我的代码?

+2

处开始阅读心理检查出来,请稍候。 ..错误:无法读取OP的头脑。发布该死的错误。 – 2011-06-16 07:21:05

+1

它已经在讨论:http://stackoverflow.com/questions/191757/c-concatenate-string-and-int – 2011-06-16 07:22:08

+0

我想获得地图其中double是分数(n/d)和字符串是(“n/d”),那么我想将它打印到文件 – torayeff 2011-06-16 07:22:46

在C++中,您必须先将int转换为string,然后才能使用+运算符将它与另一个string连接。

请参阅Easiest way to convert int to string in C++

+0

当你将非字符串类型传递给输出流时(他们会为你做转换),你不必非要这样做。 – 2011-06-16 07:23:23

+0

是的。但在OP的问题中没有任何流... – 2011-06-16 07:24:21

+0

但串联。连接非字符串值的规范C++方式是使用流。 – 2011-06-16 07:31:17

试试这个。

stringstream os; 
os << n << "/" << d; 
string s =os.str(); 
+0

这是否防止缓冲区溢出攻击? – kiltek 2013-03-09 13:29:02

使用流,你的情况,一个字符串流:

#include <sstream> 
... 
    std::stringstream ss; 
    ss << n << '/' << d; 

后来,当你的工作完成后,你可以将其存储作为一个普通的字符串:

const std::string s = ss.str(); 

重要(边)注:从不

const char *s = ss.str().c_str(); 

stringstream::str()产生临时std::string,并根据该标准,临时对象住直到表达式的结尾。然后,std::string::c_str()给你一个指向一个以null结尾的字符串的指针,但根据圣律,一旦std::string(你从中接收它)改变,那么C风格字符串将变为无效。

It might work this time, and next time, and even on QA, but explodes right in the face of your most valuable customer.

std::string必须生存,直到战斗结束:

const std::string s = ss.str(); // must exist as long as sz is being used 
const char *sz = s.c_str(); 

nd是整数。这里是你如何整数转换为字符串:

std::string s; 
std::stringstream out; 
out << n << "/" << d; 
s = out.str(); 

不像在Java中,在C++中没有operator+,一些明确转换为字符串。什么是通常位于C++做在这样的情况下是...

#include <sstream> 

stringstream ss; 
ss << n << '/' << d; // Just like you'd do with cout 
string s = ss.str(); // Convert the stringstream to a string 
+0

感谢你们所有人 – torayeff 2011-06-16 07:29:45

+0

@torayeff:继续,投票并接受答案 – 2011-06-16 07:35:51

你可以使用一个stringstream

stringstream s; 
s << n << "/" << d; 
fracs.insert(make_pair((double)n/d, s.str())); 

没有人建议它,但你也可以看看boost::lexical_cast<>

尽管此方法有时因性能问题而受到批评,但在您的情况下可能会确定,并且确实使代码更具可读性。

我认为sprintf(),这是一个函数用于发送格式化的数据字符串,将是一个更清晰的方式来做到这一点。只要你会用printf的方式,但与C风格字符串类型char *作为第一(附加)的说法:

char* temp; 
sprint(temp, "%d/%d", n, d); 
std::string g(temp); 

你可以在http://www.cplusplus.com/reference/cstdio/sprintf/