C++问题中的字符串串联

String concatenation in C++ problem

本文关键字:字符串 问题 C++      更新时间:2023-10-16

每个人我都对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();

nd是整数。以下是如何将整数转换为字符串:

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/