c++ - 如何通过strtok忽略一个字符?

标签 c++ 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 上使用 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/

相关文章:

c++ - 模板;点<2, 双>;点<3,双>

c - 使用 strtok 从 fgets 获取值

C编程strtok问题

c - 字符串格式、strtok 问题

c++ - 如何限制用户在 C++ 中将 8 个字符输入字符串(动态字符数组)?

c++ - 如何在 Windows 下轻松地将一个很长的字符串传递给工作进程?

c++ - wxWidgets + Windows 上的 Cygwin

c - 将标记添加到数组 C

c - 使用 strtok() 将数值存储在二维数组中

c++ - 尝试 'replicate' shared_ptr 向上转换行为导致复制构造函数无限递归(导致段错误)