2014-02-21 86 views
-2

我想讀取來自用戶的輸入,我知道我的方法需要一個char *但是有無論如何使cin的輸入能夠被該char使用? (看在字符* X的評論。)將字符串char *字符串讀入文件?

string y; 
cout << "Enter your file: "; 
cin >> y; 

char * x = //here is where the string needs to go. If I type in the actual address it works, but I need it to work when the user just cin's the address// 

string line,character_line; 
ifstream myfile; 
myfile.open (x); 
while(getline(myfile,line)) 
{ 
    if (line[0] != '0' && line[0] != '1') 
    { 
     character_line = line; 
    } 

} 
+0

使用std :: string :: c_str()來轉換爲一個c樣式的字符串 –

回答

1
char * x = y.c_str(); 

一個簡單的谷歌將所提供的結果:)

0

您可以簡單地使用std :: string類的c_str()方法。這工作:

#include <fstream> 
#include <iostream> 
#include <string> 

int main(void) { 
    std::string y; 
    std::cout << "Enter your file: "; 
    std::cin >> y; 
    std::string line,character_line; 
    std::ifstream myfile; 
    myfile.open (y.c_str(), std::ifstream::in); 
    while(getline(myfile,line)) 
    { 
    if (line[0] != '0' && line[0] != '1') 
    { 
     character_line = line; 
    } 

    } 
    return 0; 
} 
相關問題