c++文件读取
C++ file reading
我有一个文件,其中有一个数字,其中是后面的名称的数量。例如:
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
,提取失败,因此它停止循环。到目前为止一切顺利。
但是,流现在处于fail
状态,并且所有后续提取将失败,除非您清除错误标志。
在第一个while
循环之后写in.clear()
。
我真的不明白你为什么要写一个循环来提取一个整数。你可以直接写
if (!(in >> sp)) { /* error, no int */ }
读取名称,读取 string
s。这次可以使用循环:
std::vector<std::string> names;
std::string temp;
while (in >> temp) names.push_back(temp);
您可能需要在某处添加一个计数器,以确保名称的数量与您从文件中读取的数量匹配。
int lines;
string line;
inputfile.open("names.txt");
lines << inputfile;
for(i=0; i< lines; ++i){
if (std::getline(inputfile, line) != 0){
cout << line << std::endl;
}
}
首先,假设第一个循环:
while (in >> tmp1)
sp=tmp1;
表示读取开头的数字,这段代码应该这样做:
in >> tmp1;
根据手册operator>>
:
istream对象(*this).
提取的值或序列不返回,而是直接存储在作为参数传递的变量中
所以不要在condition中使用,而要使用:
in >> tmp1;
if( tmp1 < 1){
exit(5);
}
第二,永远不要依赖于文件格式正确的假设:
do {
in.get(tmp2);
cout << tmp2 << endl;
} while ( (tmp2 != 'n') && !in.eof());
虽然整个算法对我来说有点笨拙,但这应该可以防止无限循环。
下面是一个简单的例子,说明如何按照您想要的方式从文本文件中读取指定数量的单词。
#include <string>
#include <iostream>
#include <fstream>
void process_file() {
// Get file name.
std::string fileName;
std::cin >> fileName;
// Open file for read access.
std::ifstream input(fileName);
// Check if file exists.
if (!input) {
return EXIT_FAILURE;
}
// Get number of names.
int count = 0;
input >> count;
// Get names and print to cout.
std::string token;
for (int i = 0; i < count; ++i) {
input >> token;
std::cout << token;
}
}
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中