我正在尝试读取一个文件并将每一行分成几部分,当我尝试执行 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/