【问题标题】:How do I convert string to char array when reading a file?读取文件时如何将字符串转换为字符数组?
【发布时间】:2014-12-13 09:49:37
【问题描述】:

我想将输入文件中的字符串转换为字符数组来标记文件。这段代码可能还有其他问题,但现在,编译器说“将‘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, " ,.");
    }
}

【问题讨论】:

  • 你为什么不用std::string
  • 你如何设法使用带一个参数的strcpy函数?
  • @πάνταῥεῖ 因为我已经写过“使用命名空间 std;”在包括库之后。
  • @Mohit_Bhasi 抱歉,我实际上使用了 c_str()。这只是一个试验。
  • @FatimaTariq 我的意思不是省略命名空间限定符(顺便说一句,这是不鼓励的),我的意思是你为什么不使用它来分割成部分? strtok() 是一个危险的功能,不应使用。请参阅How to split a string in C++

标签: c++ string strtok cstring


【解决方案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).

【讨论】:

    猜你喜欢
    • 2013-10-11
    • 1970-01-01
    • 2021-12-13
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2017-12-01
    相关资源
    最近更新 更多