我有一个文件,其中有一个数字,其中是跟在后面的名字的数量。例如:
4
bob
jim
bar
ted
我正在尝试编写一个程序来读取这些名称。
void process_file(ifstream& in, ofstream& out)
{
string i,o;
int tmp1,sp;
char tmp2;
prompt_user(i,o);
in.open (i.c_str());
if (in.fail())
{
cout << "Error opening " << i << endl;
exit(1);
}
out.open(o.c_str());
in >> tmp1;
sp=tmp1;
do
{
in.get(tmp2);
} while (tmp2 != '\n');
in.close();
out.close();
cout<< sp;
}
到目前为止,我能够读取第一行并将 int 分配给 sp
我需要 sp 来计算名字的数量。我如何得到这个来读取名称。 我剩下的唯一问题是如何在忽略第一个数字的同时获取名称。 在那之前我无法实现我的循环。
最佳答案
while (in >> tmp1)
sp=tmp1;
这成功地从中读取了第一个 int
然后尝试继续。由于第二行不是int
,提取失败,所以它停止循环。到目前为止一切顺利。
但是,流现在处于失败
状态,除非清除错误标志,否则所有后续提取都将失败。
在第一个 while
循环之后立即说 in.clear()
。
不过,我真的不明白您为什么要编写一个循环来提取单个整数。你可以写
if (!(in >> sp)) { /* error, no int */ }
要读取名称,请读取 string
。这次循环没问题:
std::vector<std::string> names;
std::string temp;
while (in >> temp) names.push_back(temp);
您可能想在某处添加一个计数器,以确保名称的数量与您从文件中读取的数量相匹配。
关于C++文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15761752/