2014-02-21 41 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; 
}