2012-12-23 88 views
1

你好我有一點麻煩,此代碼輸出文件名

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

int main() 
{ 
    string line; 
    //const char* test = "connect"; 
    #define test "connect" 
    string con("c:\\filepath\\%s.txt", test); 
    ifstream file; 
    file.open(con.c_str()); 
    if (file.is_open()) { 
     while (file.good()) { 
      getline(file, line); 
      printf("setc %s\n", line.c_str()); 
      //cout << "setc " << line << endl; 
     } 
     file.close(); 
    } else 
     cout << "Unable to open file"; 
    return 0; 
} 

可能有人請告訴我,我錯了

這就是我所追求的

「騙子」是爲了從「測試」

得到它的文件名,如果你能幫助我,我將不勝感激:)

+1

''鍵通常位於鍵盤的左上角。現在您知道在哪裏可以找到它,但沒有任何東西阻止您使用它。 – 2012-12-23 09:22:40

回答

3

有很多方法可以做到這一點。這裏有兩個:

std::string con1("c:\\filepath\\" test ".txt"); 
std::string con2("c:\\filepath\\" + std::string(test) + ".txt"); 

con1初始化要求test就成了一個字符串通過宏觀擴張的文字,因爲它依賴於字符串文字的合併。第二種形式更一般,test可以是任何可以轉換爲std::string的東西,例如char const*

+0

非常感謝你,請你告訴我你曾經這樣做過的形式?像這種代碼的風格是什麼 – Jork449

+0

我更喜歡第二種形式,因爲我不使用常量的宏。當然,如果你使用'std :: string const test(「connect」);'爲你直接添加它的常量。 –