简体   繁体   中英

string concatenate question in C++

I want to concatenate a fileName including path and file names. Then I can open and write it. But I failed to do so.

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();
string str = "test.txt";
char *buf = new char[strlen(str)];
strcpy(buf,str);

Should rather be

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

But after all, you don't even need that. A std::string supports concatenation by operator+= and construction from a char* and exposes a c_str function that returns a c-style string:

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

ofstream outfile;
outfile.open(str.c_str());
#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";
}
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();
string fullName = string(pPath) + "/" + ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM