我想将字符串从输入文件转换为char数组以标记文件。这段代码可能有其他问题但是现在,编译器说“将'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, " ,.");
}
}
答案 0 :(得分: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)