c++ - 在 C++ 中读取文件时没有得到正确的输出

标签 c++ iostream fstream

我正在帮助一个 friend 完成一个关于读取文件并打印它的简单 C++ 任务,代码如下:

#include<iostream>
#include<cstdlib>
#include<fstream>

using namespace std;
const int P=10;
struct persona
{
    string nombre;
    int puntos;
};
typedef persona vec[P];


int main (void)
{

    ifstream f;
    vec v;
    int i;

    f.open("estadisticas2.txt");
    if(!f)
    cout<<"Error abriendo fichero\n";
    else
    {
        for(i=0;i<P;i++)
        {  
            getline(f,v[i].nombre);
            f >> v[i].puntos;
            f.ignore(); 

        } 
         f.close(); 
        for(i=0;i<P;i++)
         {
            cout<<v[i].nombre<<"\n";
            cout<<v[i].puntos<<"\n";
        }

    }
    system("pause");
    return 0;
}      

我检查了是否是因为无法读取或 for 循环未按正确时间运行的问题。还初始化了 vector v,但我只得到这个输出:

unknown 
0
pene
20
ojete
40
tulia
240

0

1875655176

0

16

-1

1875658144

代替(真正的 .txt 值):

unknown 
0
pene
20
ojete
40
tulia
240 
Ano 
2134
lolwut
123
unknown 
0 
unknown 
0 
unknown 
0 
unknown 
0                                                                                                                                                                                                                            

谢谢你所做的一切!

最佳答案

您的 f.ignore() 会丢弃一个字符,您认为它是换行符,但在您的输入文件中:

unknown 
0
pene
20
ojete
40
tulia
240 <=== here
Ano 
2134
lolwut
123
unknown 
0 <=== here
unknown 
0 <=== here
unknown 
0 <=== here
unknown 
0 <=== here

上面标记的所有地方都有一个尾随空格尾随换行符。要在提取号码后消耗一切,您应该使用:

f.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

这将丢弃输入流中的所有内容,包括下一个换行符,从而占用空间并保持您的行相对位置不变。

作为旁注,您还应该检查您的 IO 操作以获取 getline 和数字提取。

关于c++ - 在 C++ 中读取文件时没有得到正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27667642/

相关文章:

c++ - 编译器在声明类时显示未定义的结构错误

c++ - C++派生类访问基类的好友运算符

c++ - 是否可以同时在两个对象上使用插入运算符?

c++ - 如何将带有 ID 号的名称列表读入 map C++

C++ 不会告诉您动态数组的大小。但为什么?

c++ - 如何检查 Void 指针是否可以转换为其他特定指针类型?

c++ - 如何删除 "NSBundle may not respond to ' -pathForResource :ofType' "warning

c++ - iostream 或 C++ 中的其他地方是否有称为时间的东西?

c++ - 'ios' : is not a class or namespace name

c++ - 将文本文件中的整数插入整数数组