Ete*_*ner 5 c++ string tokenize strtok
在下面的程序中,我打算将文件中的每一行读成一个字符串,分解字符串并显示单个单词.我面临的问题是,程序现在只输出文件中的第一行.我不明白为什么会这样?
#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<<" ";
}
}
}
Run Code Online (Sandbox Code Playgroud)
我是 C++ 新手,但我认为另一种方法可能是:
while(getline(InputFile, store))
{
stringstream line(store); // include <sstream>
string token;
while (line >> token)
{
cout << "Token: " << token << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这将逐行解析文件并根据空格分隔标记每一行(因此这不仅包括空格,例如制表符和换行符)。