C++中的字符串拼接问题

4

我想将包含路径和文件名的文件名连接起来,然后打开并写入它。但是我没有成功。

char * pPath;
pPath = getenv ("MyAPP");
if (pPath!=NULL)
//printf ("The current path is: %s",pPath); // pPath = D:/temp

string str = "test.txt";
char *buf = new char[strlen(str)];
strcpy(buf,str);

fullName = ??  // how can I get D:/temp/test.txt 

ofstream outfile;
outfile.open(fullName);
outfile << "hello world" << std::endl;

outfile.close();

你到底为什么要使用 char 缓冲区和 strcpy 函数?! - Lightness Races in Orbit
4个回答

4
string str = "test.txt";
char *buf = new char[strlen(str)];
strcpy(buf,str);

应该改为

string str = "test.txt";
char *buf = new char[str.size() + 1];
strcpy(buf,str.c_str());

但是,你其实不需要那个。一个 std::string 支持通过 operator+= 进行串联,可以从 char* 构建并公开一个返回 c 风格字符串的 c_str 函数:

string str(pPath); // construction from char*
str += "test.txt"; // concatenation with +=

ofstream outfile;
outfile.open(str.c_str());

实际上应该是 new char[str.size() + 1] -- 不要忘记在末尾加上空字节。 - Ernest Friedman-Hill
@Ernest:我不知道你的意思... ;) - Xeo

1
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;

int main() {
    char* const my_app = getenv("MyAPP");
    if (!my_app) {
        cerr << "Error message" << endl;
        return EXIT_FAILURE;
    }
    string path(my_app);
    path += "/test.txt";
    ofstream out(path.c_str());
    if (!out) {
        cerr << "Error message" << endl;
        return EXIT_FAILURE;
    }
    out << "hello world";
}

1
char * pPath;
pPath = getenv ("MyAPP");
string spPath;
if (pPath == NULL)
  spPath = "/tmp";
else
  spPath = pPath;

string str = "test.txt";

string fullName = spPath + "/" +  str;
cout << fullName << endl;

ofstream outfile;
outfile.open(fullName.c_str());
outfile << "hello world" << std::endl;

outfile.close();

0
string fullName = string(pPath) + "/" + ...

string fullName(pPath);
fullName += "/";
fullName += ...;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接