2011-05-12 78 views
4

我想連接一個包含路徑和文件名的文件名。然後我可以打開並寫下它。但我沒有這樣做。C++中的字符串連接問題

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

上你究竟使用'char'緩衝和'的strcpy '爲?! – 2011-05-31 09:18:26

回答

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_str函數返回一個C風格的字符串:

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

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

實際上它應該是'new char [str.size()+ 1]' - 不要忘記最後的空字節。 – 2011-05-12 02:56:37

+0

@ Ernest:我不明白你的意思......;) – Xeo 2011-05-12 02:57:20

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

string fullName(pPath); 
fullName += "/"; 
fullName += ...; 
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();