strcmp的分段错误

0 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))
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 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;
}
Run Code Online (Sandbox Code Playgroud)