2011-06-16 159 views
1

大家我有一個字符串連接問題在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

回答

2

在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

2

試試這個。

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

這是否防止緩衝區溢出攻擊? – kiltek 2013-03-09 13:29:02

2

使用流,你的情況,一個字符串流:

#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(); 
0

nd是整數。這裏是你如何整數轉換爲字符串:

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

不像在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

0

你可以使用一個stringstream

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

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

儘管此方法有時因性能問題而受到批評,但在您的情況下可能會確定,並且確實使代碼更具可讀性。

0

我認爲sprintf(),這是一個函數用於發送格式化的數據字符串,將是一個更清晰的方式來做到這一點。只要你會用printf的方式,但與C風格字符串類型char *作爲第一(附加)的說法:

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

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