如何通过 strtok 忽略字符

How to ignore a character through strtok?

本文关键字:字符 strtok 何通过      更新时间:2023-10-16

在下面的代码中,我也想忽略字符" .但是在添加它之后,我仍然得到"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 字符,并在行尾留下垃圾。