在下面的代码中,我还想忽略字符 ” 。但添加后,我仍然得到“Mr_Bishop”作为我的输出。
我有以下代码:
ifstream getfile;
getfile.open(file,ios::in);
char data[256];
char *line;
//loop till end of file
while(!getfile.eof())
{
//get data and store to variable data
getfile.getline(data,256,'\n');
line = strtok(data," ”");
while(line != NULL)
{
cout << line << endl;
line = strtok(NULL," ");
}
}//end of while loop
我的文件内容:
hello 7 “Mr_Bishop”
hello 10 “0913823”
基本上我想要的输出是:
hello
7
Mr_Bishop
hello
10
0913823
使用此代码我只能得到:
hello
7
"Mr_Bishop"
hello
10
"0913823"
提前致谢! :)
我意识到我在内部循环中犯了一个错误,遗漏了引用。但现在我收到以下输出:
hello
7
Mr_Bishop
�
hello
10
0913823
�
有什么帮助吗?谢谢! :)
最佳答案
看起来您使用了写字板或其他东西来生成该文件。您应该在 Windows 上使用 Notepad 或 Notepad++,或者在 Linux 上使用类似的工具来创建 ASCII 编码。现在您正在使用看起来像 UTF-8 的编码。
此外,“正确的转义序列是\”。例如
line = strtok(data," \"");
将文件修复为 ASCII 编码后,您会发现循环中遗漏了一些内容。
while(!getfile.eof())
{
//get data and store to variable data
getfile.getline(data,256,'\n');
line = strtok(data," \"");
while(line != NULL)
{
std::cout << line << std::endl;
line = strtok(NULL," \""); // THIS used to be strtok(NULL," ");
}
}//end of while loop
您错过了那里的一组引言。 更正文件和此错误会产生正确的输出。
关于c++ - 如何通过strtok忽略一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607743/