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<<" ";
        }

    }

}
4

3 回答 3

3

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

while(getline(InputFile, store))
{
    stringstream line(store); // include <sstream>
    string token;        

    while (line >> token)
    {
        cout << "Token: " << token << endl;
    }
}

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

于 2010-06-21T02:28:37.957 回答
2

嗯,这里有一个问题。 strtok()接受一个以 null 结尾的字符串,并且 a 的内容std::string不一定以 null 结尾。

std::string您可以通过调用它从a 中获取一个以null 结尾的字符串c_str(),但这会返回a const char*(即,该字符串是不可修改的)。 strtok()接受 achar*并在调用时修改字符串。

如果您真的想使用strtok(),那么在我看来,最干净的选择是将字符从 a 复制std::string到 astd::vector中,然后以空值终止向量:

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

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

如果您可以使用 Boost,我建议您使用Boost Tokenizer。它为标记字符串提供了一个非常干净的接口。

于 2010-06-21T02:17:32.113 回答
0

詹姆斯麦克内利斯所说的是正确的。

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

string store

利用

const int MAX_SIZE_LINE = 1024; //or whatever value you consider safest in your context.
char store[MAX_SIZE_LINE];
于 2010-06-21T02:27:40.123 回答