2013-07-23 53 views
0

我希望能夠以char *形式將常量字符串附加到另一個字符串的末尾,然後將結果字符串用作open()的參數。這裏是什麼樣子:結合靜態char *和常量字符串

file1.cpp

#include "string.h" 

file2 foo; 

char* word = "some"; 
foo.firstWord = word; //I want the file2 class to be able to see "some" 

file2.h

#include <fstream> 
#include <iostream> 

#define SECONDWORD "file.txt" 

class file2{ 
public: 
    file2(); 
    static char* firstWord; 
    static char* fullWord; 

private: 
    ofstream stream; 

} 

file2.cpp

#include "file2.h" 

char* file2::firstWord; 
char* file2::fullWord; 

fullWord = firstWord + SECONDWORD; //so fullWord is now "somefile.txt" ,I know this doesn't work, but basically I am trying to figure out this part 

file2::file2(){ 
    stream.open(fullWord); 
} 

所以我不是在C十分精通++,所以任何幫助將不勝感激!

回答

1

C++風格的解決方案可能如下。

#include <string> 

char* a = "file"; 
char* b = ".txt"; 

... 

stream.open((std::string(a) + b).c_str()); 

這裏會發生什麼?首先,std::string(a)創建一個臨時對象std::string。值已添加到它。最後,c_str()方法返回一個c風格的字符串,其中包含a + b

相關問題