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

时间:2011-05-12 02:50:17

标签: c++ string concatenation

我想连接一个包含路径和文件名的fileName。然后我可以打开并写出来。但我没有这样做。

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

4 个答案:

答案 0 :(得分: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());

答案 1 :(得分: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";
}

答案 2 :(得分: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();

答案 3 :(得分:0)

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

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