c++文件读取

C++ file reading

本文关键字:读取 文件 c++      更新时间:2023-10-16

我有一个文件,其中有一个数字,其中是后面的名称的数量。例如:

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 */ }

读取名称,读取 strings。这次可以使用循环:

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;
    }
}