首页 文章

在程序中一起使用getline和strtok的问题

提问于
浏览
5

在下面的程序中,我打算将文件中的每一行读成一个字符串,分解字符串并显示单个单词 . 我面临的问题是,程序现在只输出文件中的第一行 . 我不明白为什么会这样?

#include<iostream>
#include<string>
#include<fstream>
#include<cstdio>
using namespace std;

int main()
{
    ifstream InputFile("hello.txt") ;
    string store ;
    char * token;

    while(getline(InputFile,store))
    {
        cout<<as<<endl;
        token = strtok(&store[0]," ");
        cout<<token;
        while(token!=NULL)
        {
        token = strtok(NULL," ");
        cout<<token<<" ";
        }

    }

}

3 回答

  • 0

    James McNellis所说的是正确的 .

    为了快速解决方案(虽然不是最好的),而不是

    string store
    

    使用

    const int MAX_SIZE_LINE = 1024; //or whatever value you consider safest in your context.
    char store[MAX_SIZE_LINE];
    
  • 3

    我是C的新手,但我认为另一种方法可能是:

    while(getline(InputFile, store))
    {
        stringstream line(store); // include <sstream>
        string token;        
    
        while (line >> token)
        {
            cout << "Token: " << token << endl;
        }
    }
    

    这将逐行解析您的文件并基于空格分隔标记每一行(因此这不仅包括空格,例如制表符和新行) .

  • 2

    嗯,这里有一个问题 . strtok() 采用以null结尾的字符串,并且 std::string 的内容不一定以空值终止 .

    您可以通过调用 c_str()std::string 获取以null结尾的字符串,但这会返回 const char* (即字符串不可修改) . strtok() 接受 char* 并在调用时修改字符串 .

    如果你真的想使用 strtok() ,那么在我看来最干净的选择是将 std::string 中的字符复制到 std::vector 并将null终止向量:

    std::string s("hello, world");
    std::vector<char> v(s.begin(), s.end());
    v.push_back('\0');
    

    您现在可以使用向量的内容作为以null结尾的字符串(使用 &v[0] )并将其传递给 strtok() .

    如果你可以使用Boost,我建议使用Boost Tokenizer . 它为标记字符串提供了一个非常干净的界面 .

相关问题