2014-12-13 98 views
0

我想将字符串从输入文件转换为字符数组来标记文件。此代码可能有其他问题,但现在,编译器说“将const char *赋值给char [100]'的不兼容类型”。如何在读取文件时将字符串转换为字符数组?

string filename = "foo.txt"; 
ifstream data(filename.c_str()); 
string temp; 
char str[100]; 
char* pch; 
while (getline(data, temp)){ 
    str = temp.c_str(); 
    pch = strtok(str, " ,."); 
    while (pch != NULL){ 
     cout << pch << endl; //Or something else, Haven't gotten around to this part yet. 
     pch = strtok (NULL, " ,."); 
    } 
} 
+3

为什么不使用'std :: string'? – 2014-12-13 09:51:37

+0

你如何设法使用带一个参数的strcpy函数? – 2014-12-13 09:53:40

+0

@πάνταῥεῖ因为我已经写过“using namespace std;”包括图书馆之后。 – 2014-12-13 10:00:16

回答

1

我知道这并不能回答你的问题,但答案是真的:做一个不同的方式,因为你是在伤害的世界,如果你要跟你在做什么.. 。

您可以处理此没有任何神奇数字或生数组:

const std::string filename = "foo.txt"; 
std::ifstream data(filename.c_str()); 
std::string line; 
while(std::getline(data, line)) // #include <string> 
{ 
    std::string::size_type prev_index = 0; 
    std::string::size_type index = line.find_first_of(".,"); 
    while(index != std::string::npos) 
    { 
    std::cout << line.substr(prev_index, index-prev_index) << '\n'; 
    prev_index = index+1; 
    index = line.find_first_of(".,", prev_index); 
    std::cout << "prev_index: " << prev_index << " index: " << index << '\n'; 
    } 
    std::cout << line.substr(prev_index, line.size()-prev_index) << '\n'; 
} 

此代码不会赢得任何贝蒂或效率的比赛,但它肯定不会在意想不到的输入崩溃。 Live demo here (using an istringstream as input instead of a file)

相关问题