如何从C ++中的char读取文件char? [英] How to read from a file char by char in C++?

查看:129
本文介绍了如何从C ++中的char读取文件char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个文件读取,但我唯一的工作是使用getline()。

I'm trying to read from a file, but the only thing I get on working is using getline().

问题是读一个整行

我的输入文件如下所示:

My input file looks like this:

abc 10 20
bbb 10        30
ddd 40 20

每行中的第一个字应该保​​存为字符串,后面的数字都为int。
每行中的单词之间的分隔符可以是空格或TAB。

when the first word in each line should be saved as a string, and both number afterwards as ints. The delimiter between the "words" in each line can be either a SPACE or a TAB.

那么唯一的解决方案是通过char读取char?或者有其他解决方案?

So is the only solution is reading char by char? Or is there another solution?

推荐答案

假设你想要这样的:

std::string s;
int         v0, v1;
while (in >> s >> v0 >> v1) {
    std::cout << "do something with s='" << s << "' v0=" << v0 << " v1=" << v1 << "\n";
}

这不能确保这些值都在一行上,但是。如果你想安排这个,你可能想使用 std :: getline()读取一行,然后使用 std :: istringstream

This doesn't make sure that the values are all on one line, however. If you want to arrange for this you probably want to read a line using std::getline() and then split this line up as above using an std::istringstream.

这篇关于如何从C ++中的char读取文件char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆