我一直在搞乱这段代码几个小时,正在寻找一些建议。我正在使用 strtok 从字符串中获取单词,但我不断在每一行的末尾获取额外的数据。我有以下代码:
cout << "\n\n6. Load File:\n";
getline(cin, inFile);
inFile = path + inFile;
myfile.open(inFile.c_str());
while (myfile.is_open() == false) //check to make sure file exists
{
cout << "\nPlease enter in a valid file name: ";
getline(cin,inFile);
inFile = path + inFile;
myfile.open(inFile.c_str());
}
getline (myfile,line);
while ( myfile.good() ) //while the file is running, run below code
{
getline (myfile,line);
//cout << line;
char str[line.length()];
char * pch;
for (int i=0;i<line.size();i++) { //creates a char array from characters
str[i]=line[i];
}
pch = strtok(str," ,-!?\r\t\f\v\n\0|/\\_"); //eliminates whitespace,etc in char array
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,-!?\r\t\f\v\n\0|/\\_"); //grabs next word
}
}
myfile.close();
现在这段代码给了我我想要的单词输出,但在每一行的末尾都有来自内存的随机疯狂值。见下文:
加载文件:
cars1.txt
Jalopy
Blue
3402.99 \244\363P
Rustbucket
Brown
44.99 P
Lemon
Yellow
4226.99 99P
请帮助,非常感谢!