[英]reading from istringstream using getline and maybe strtok somehow?
[英]Problem with using getline and strtok together in a program
在下面的程序中,我打算將文件中的每一行讀取為一個字符串,分解該字符串並顯示各個單詞。我面臨的問題是,該程序現在僅輸出文件中的第一行。 我不明白為什么會這樣?
#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<<" ";
}
}
}
我是C ++的新手,但我認為替代方法可能是:
while(getline(InputFile, store))
{
stringstream line(store); // include <sstream>
string token;
while (line >> token)
{
cout << "Token: " << token << endl;
}
}
這將逐行解析文件,並根據空格分隔標記每一行(因此,不僅包括空格,例如制表符和換行符)。
好吧,這里有個問題。 strtok()
接受以null終止的字符串,並且std::string
的內容不一定以null終止。
您可以通過在std::string
調用c_str()
來獲取以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 。 它為標記字符串提供了非常干凈的接口。
James McNellis所說的是正確的。
快速解決方案(雖然不是最好的),而不是
string store
使用
const int MAX_SIZE_LINE = 1024; //or whatever value you consider safest in your context.
char store[MAX_SIZE_LINE];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.