c++ - 使用strtok函数时出现的问题

标签 c++

大家早上好:)

我用 C++ 编写了一段代码,可以从 txt 文件中读取信息。它获取第一行中的信息,将其保存在一个字符串中,然后我想使用这些信息。我想读这个字符串,当它找到一个“|”字符它必须跳到一个新行。这很简单,但是我在执行时遇到了问题,我已经尝试了几个小时来寻找问题,但我没有成功。 :( 我附上了代码。

预先感谢您的帮助。

#include <string>
#include <fstream>
#include <vector>
#include <iostream>

using namespace std;

int main()
{

    ifstream ifs( "C:\\a\\text.txt" );
    string temp;

    getline( ifs, temp ); 
    cout<<temp<<endl;

    string * pch;
    pch = strtok (temp,"|");

    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, "|");
    }

    system("pause");
    return 0;

}

最佳答案

strtok 使用 char*,而不是 string*。这可能就是您遇到问题的原因。

由于您是用 C++ 实现的,我建议您使用字符串函数而不是 strtok:

int main()
{

    ifstream ifs( "C:\\a\\text.txt" );
    string temp;

    getline( ifs, temp ); 
    cout<<temp<<endl;

    size_t tokenPos = temp.find("|");   

    while (tokenPos != string::npos)
    {
        cout << temp.substr(0, tokenPos) << endl;
        temp.erase(0, tokenPos+1);
        tokenPos = temp.find("|");  
    }

    system("pause");
    return 0;

}

要将您的文本存储在您在评论中描述的值中,您需要执行以下操作:

int main() 
{ 
    ifstream ifs( "C:\\a\\text.txt" ); 

    int id; 
    int type; 
    int columns; 
    string temp; 

    getline( ifs, temp ); 
    cout<<temp<<endl; 

    size_t tokenPos = temp.find("|");
    while (tokenPos != string::npos) 
    { 
        int i=0; 
        tokenPos = temp.find("|"); 
        cout << temp.substr(0, tokenPos) << endl; 

        if(i==0)
        { 
            id = atoi(temp.substr(0, tokenPos).c_str()); 
        }
        else if(i==1) 
        { 
            type = atoi(temp.substr(0, tokenPos).c_str()); 
        } 
        else if(i==2) 
        { 
            columns = atoi(temp.substr(0, tokenPos).c_str()); 
        } 

        ++i; 
        temp.erase(0, tokenPos+1); 
    } 

    cout << "ID: " << id << ", Type: " << type << ", Columns: " << columns << endl; 
    system("pause"); 
    return 0; 
}

关于c++ - 使用strtok函数时出现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4920424/

相关文章:

c++ - 在 C++ 模板特化中添加基类

c++ - OpenGL:天空盒放大太多

c++ - 使用 std::function 或转发引用作为高阶函数的通用可调用对象输入参数?

c++ - 尝试加载自定义 mysql 插件时 undefined reference - 如何调试?

c++ - libneo4j-client 无法关闭并重新打开新 session ?

c++ - 为什么要在枚举上抛出一个类?

c++ - 求两个 x1,x2 之间的质数总数,找不到错误?

c++ - Eclipse 自动生成 Doxygen 注释配置

c++ - 为什么容器节点不能在wxDataViewCtrl中有多个列

c++ - 如何在 Windows 中用 C++ 创建定时器