C++ 在程序中同时使用getline和strtok的问题

C++ 在程序中同时使用getline和strtok的问题,c++,string,tokenize,strtok,C++,String,Tokenize,Strtok,在下面的程序中,我打算将文件中的每一行读入一个字符串,分解字符串并显示单个单词。我面临的问题是,程序现在只输出文件中的第一行。我不明白为什么会这样 #include<iostream> #include<string> #include<fstream> #include<cstdio> using namespace std; int main() { ifstream InputFile("hello.txt") ; stri

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

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

    }

}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
ifstream输入文件(“hello.txt”);
字符串存储;
字符*令牌;
while(getline(输入文件、存储))
{

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

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

如果您真的想使用
strtok()
,那么我认为最干净的选择是将
std::string
中的字符复制到
std::vector
中,空值终止向量:

std::string s("hello, world");
std::vector<char> v(s.begin(), s.end());
v.push_back('\0');
std::string s(“你好,世界”);
向量v(s.begin(),s.end());
v、 推回('\0');
现在,您可以将向量的内容用作以null结尾的字符串(使用
&v[0]
),并将其传递给
strtok()


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

James McNellis所说的是正确的

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

string store
使用


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

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

    while (line >> token)
    {
        cout << "Token: " << token << endl;
    }
}
while(getline(输入文件、存储))
{
stringstream行(存储);//包括
字符串标记;
while(行>>标记)
{

cout同意:如果OP的实际用例是一个简单的问题(在空格上拆分),那么stringstream是一个非常好的主意。我想知道为什么要进行向下投票;我认为使用向量保证的连续性。
while(getline(InputFile, store))
{
    stringstream line(store); // include <sstream>
    string token;        

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