C++逐行读取文件,然后使用分隔符分割每一行
我想逐行读取txt文件,读取每一行后,我想根据选项卡“\t”分割该行,并将每个部分添加到结构中的元素中。
我的结构是 1*char 和 2*int
struct myStruct
{
char chr;
int v1;
int v2;
}
,其中 chr 可以包含多个字符。
一行应该是这样的:
randomstring TAB number TAB number NL
I want to read a txt file line by line and after reading each line, I want to split the line according to the tab "\t" and add each part to an element in a struct.
my struct is 1*char and 2*int
struct myStruct
{
char chr;
int v1;
int v2;
}
where chr can contain more than one character.
A line should be something like:
randomstring TAB number TAB number NL
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试:
注意:如果 chr 可以包含多于 1 个字符,则使用字符串来表示。
Try:
Note: if chr can contain more than 1 character then use a string to represent it.
除非您也打算在 C 中使用此结构,否则我会将预期的 char* 替换为 std::string。
接下来,因为我打算能够从流中读取它,所以我将编写以下函数:
使用 str 作为 std::string 成员。这将写入您的结构,使用制表符作为第一个分隔符,然后任何空白分隔符将在接下来的两个整数之前执行。 (您可以强制它使用选项卡)。
要逐行读取,您可以继续读取这些内容,或者先将行读取到字符串中,然后将字符串放入 istringstream 中并调用上面的代码。
您需要决定如何处理失败的读取。上述任何失败的读取都会使流处于失败状态。
Unless you intend to use this struct for C as well, I would replace the intended char* with std::string.
Next, as I intend to be able to read it from a stream I would write the following function:
with str as the std::string member. This writes into your struct, using tab as the first delimiter and then any white-space delimiter will do before the next two integers. (You can force it to use tab).
To read line by line you can either continue reading these, or read the line first into a string then put the string into an istringstream and call the above.
You will need to decide how to handle failed reads. Any failed read above would leave the stream in a failed state.
我在遵循此处的一些建议时遇到了一些困难,因此我发布了一个在制表符分隔文件上重载结构的输入和输出运算符的完整示例。作为奖励,它还从 stdin 或通过命令参数提供的文件获取输入。
我相信这在遵守运算符语义的同时非常简单。
pairwise.h
pairwise.cc
test.cc
编译
使用
I had some difficulty following some of the suggestions here, so I'm posting a complete example of overloading both input and output operators for a struct over a tab-delimited file. As a bonus, it also takes the input either from
stdin
or from a file supplied via the command arguments.I believe this is about as simple as it gets while adhering to the semantics of the operators.
pairwise.h
pairwise.cc
test.cc
Compiling
Usage