C++问题中的字符串串联
String concatenation in C++ problem
每个人我都对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));
}
如何修复我的代码?
这样试试。
stringstream os;
os << n << "/" << d;
string s =os.str();
在C++中,必须先将int
转换为string
,然后才能使用+运算符将其与另一个string
连接。
请参阅C++中将int转换为字符串的最简单方法。
使用流,在您的情况下,使用字符串流:
#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风格的字符串就会无效。
这一次,下一次,甚至在QA上都可能奏效,但在你最有价值的客户面前,它会爆炸。
std::string
必须生存到战斗结束:
const std::string s = ss.str(); // must exist as long as sz is being used
const char *sz = s.c_str();
n
和d
是整数。以下是如何将整数转换为字符串:
std::string s;
std::stringstream out;
out << n << "/" << d;
s = out.str();
您可以使用字符串流。
stringstream s;
s << n << "/" << d;
fracs.insert(make_pair((double)n/d, s.str()));
目前还没有人提出建议,但您也可以看看boost::lexical_cast<>
。
虽然这种方法有时会因为性能问题而受到批评,但在您的情况下它可能还可以,而且它肯定会使代码更可读。
与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
我认为sprintf()是一个用于将格式化数据发送到字符串的函数,它将是一种更清晰的方法。就像使用printf一样,但使用c样式字符串类型char*作为第一个(附加)参数:
char* temp;
sprint(temp, "%d/%d", n, d);
std::string g(temp);
你可以在http://www.cplusplus.com/reference/cstdio/sprintf/
- setlocale的C++土耳其字符串问题
- C++字符串问题-如何访问字符串元素
- 提升,从字符串问题中获得时间
- 字符串问题中的系统( "command" ) 字符串
- 从文件和字符串问题中读取
- 将C++函数转换为 C#(字符串问题)
- 有关字符串C++问题
- Visual Studio和Xcode之间的Chaiscript字符串问题
- 回文字符串问题:为什么我必须放+1而不是-1才能让这个代码工作
- Dll导入Marshal C++字符串问题
- 崩溃:字符串问题
- 正在寻找另一种解决二进制字符串问题的尝试
- C++ Win32 是字符串问题
- 迭代器字符串问题
- Python 3:Python/C API字符串问题
- 带有空格的C++字符串问题
- 有些字符串问题
- C++11 std::regex_replace()创建带有特定字符串问题的regexp
- Turbo C++的字符串问题
- 棘手的子字符串问题