如何通过 strtok 忽略字符
How to ignore a character through strtok?
在下面的代码中,我也想忽略字符" .但是在添加它之后,我仍然得到"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上使用记事本或记事本++,或者在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
你在那里错过了一组引号。更正文件和此错误会产生正确的输出。
非常仔细地查看您的代码:
line = strtok(data," ”");
注意引号如何倾斜在不同的角度(好吧,我的,我想希望你的字体显示同样的东西)。您在strtok()
调用中仅包含结束双引号。但是,您的数据文件具有:
hello 7 “Mr_Bishop”
它有两种不同类型的报价。确保使用所有正确的字符,无论数据"正确"是什么。
更新:您的数据可能是 UTF-8 编码的(这就是您在那里获得那些倾斜双引号的方式),并且您正在使用完全不知道 UTF-8 编码的strtok()
。所以它可能在做错事,拆分多字节 UTF-8 字符,并在行尾留下垃圾。
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++ 使用 Strtok 读取字符串字符时出错
- 将 strtok 分隔符设置为两个字符
- 如何通过 strtok 忽略字符
- 如何使用字符串argument而不是字符数组来使用strtok()