c++ - strcmp 的段错误

标签 c++

我正在尝试读取一个文件并将每一行分成几部分,当我尝试执行 strcmp 或 strncmp 时,我遇到了段错误。谁能帮我解决这个问题?

char *input_file = argv[1];
char *line;
char *type = NULL;
ifstream infile;
infile.open(input_file, ifstream::in);
while(!infile.eof())
{
    std::string s;
    std::getline(infile, s);
    line = new char[s.length()+1];
    strcpy(line, s.c_str());
    type = strtok(line,"(");
    cout<<"type"<<type<<"\n";
    if(s.size()>0)
        s.resize(s.size()-1);
    if(s[0]=='#')
        continue;
    if(!strncmp(type,"INPUT",5))

最佳答案

这对于字符串(和流)来说可能容易得多,而且肯定更“C++”:

std::string line;

while (std::getline(infile, line))
{
  // process "line", e.g. by tokenizing:
  std::istringstream iss(line);
  std::string token;
  while (iss >> token)
  {
    // process token, e.g. use token.substr(...)
  }

  // or directly, as a whole:
  std::cout << line.substr(line.find_first_of('(') + 1) << std::endl;
}

关于c++ - strcmp 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379414/

相关文章:

c++ - 寻找一种更好的方法来表示无符号字符数组

java - Matlab 函数 'quad' 在 Java 和 C++ 中可用吗?

c++ - QT 5 connect() 函数连接文本编辑器和主窗口

c++ - Clion Intel C++ 编译器设置

C++:复制到解除引用的指针

c++ - 如何声明一个函数,它是一个类的成员并返回一个指向线程的函数指针?

c++ - C++ 中的基本 if 语句 3 值

c++ - 从 float* 转换为 vector<float >

C++ 使用自定义比较函数初始化 priority_queue

c++ - 降低 C++ 中的圈复杂度