在程序中同时使用 getline 和 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<<" ";
}
}
}
In the below program , I intend to read each line in a file into a string , break down the string and display the individual words.The problem I am facing is , the program now outputs only the first line in the file. I do not understand why this is happening ?
#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<<" ";
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我是 C++ 新手,但我认为另一种方法可能是:
这将逐行解析文件并根据空格分隔标记每一行(因此这不仅包括空格,例如制表符和新行)。
I'm new to C++, but I think an alternative approach could be:
This will parse your file line-by-line and tokenise each line based on whitespace separation (so this includes more than just spaces, such as tabs, and new lines).
嗯,这里有一个问题。
strtok()
接受一个以 null 结尾的字符串,而std::string
的内容不一定以 null 结尾。您可以通过调用
c_str()
从std::string
获取以 null 结尾的字符串,但这会返回const char*
(即该字符串不可修改)。strtok()
接受一个char*
并在调用时修改字符串。如果您确实想使用 strtok(),那么在我看来,最干净的选择是将字符从 std::string 复制到 std: :vector 和以 null 结尾的向量:
您现在可以使用向量的内容作为以 null 结尾的字符串(使用
&v[0]
)并将其传递给 <代码>strtok()。如果您可以使用 Boost,我建议使用 Boost Tokenizer< /a>.它提供了一个非常干净的接口来标记字符串。
Well, there is a problem here.
strtok()
takes a null-terminated string, and the contents of astd::string
are not necessarily null-terminated.You can get a null-terminated string from a
std::string
by callingc_str()
on it, but this returns aconst char*
(i.e., the string is not modifiable).strtok()
takes achar*
and modifies the string when it is called.If you really want to use
strtok()
, then in my opinion the cleanest option would be to copy the characters from thestd::string
into astd::vector
and the null-terminate the vector:You can now use the contents of the vector as a null-terminated string (using
&v[0]
) and pass that tostrtok()
.If you can use Boost, I'd recommend using Boost Tokenizer. It provides a very clean interface for tokenizing a string.
詹姆斯·麦克内利斯所说的是正确的。
对于快速解决方案(虽然不是最好的),而不是
使用
What James McNellis says is correct.
For a quick solution (though not the best), instead of
use