c++ - 读取文件时如何将字符串转换为字符数组?

标签 c++ string strtok cstring

我想将字符串从输入文件转换为字符数组以标记文件。这段代码可能还有其他问题,但就目前而言,编译器会提示“将‘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, " ,.");
    }
}

最佳答案

我知道这不能回答你的问题,但答案确实是:换一种方式,因为如果你继续做你正在做的事情,你就会陷入一个受伤的世界......

你可以在没有任何魔数(Magic Number)或原始数组的情况下处理这个问题:

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) .

关于c++ - 读取文件时如何将字符串转换为字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457550/

相关文章:

c++ - curlpp 链接错误

c++ - move 的 vector 总是空的吗?

C++/模板/模板类型的显式初始化?

c - strtok 内部的 strtok 无法使用原始 token 的副本 - C

c++ - 如何将 C 字符串拆分为 C 字符串数组

c - 如何在 C 字符串中嵌入双引号?

c++ - 在 Debug模式下使用 boost 库的发布版本

c++ - 检查字符串中每个字符串有多少个(简化)

JavaScript:String 和 Array 上 indexOf 方法的效率差异

python - 使用新的 Python 格式函数舍入小数