【问题标题】:Not getting the right output reading a file in c++在 C++ 中读取文件时没有得到正确的输出
【发布时间】:2014-12-27 13:21:02
【问题描述】:

我正在帮助一个朋友完成一个关于读取文件和打印文件的简单 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 循环没有正确运行的问题。还初始化了向量v,但我只得到这个输出:

unknown 
0
pene
20
ojete
40
tulia
240

0

1875655176

0

16

-1

1875658144

Insted of(真正的 .txt 值):

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

感谢一切!

【问题讨论】:

  • 由于 getline 刷新换行符,您是否尝试过不使用 f.ignore()?
  • 是的,我做到了,结果更糟。

标签: c++ iostream fstream


【解决方案1】:

您的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 和数字提取。

【讨论】:

  • 我会尽快尝试,谢谢你的时间朋友!
【解决方案2】:
{
  getline(f, v[i].nombre);
  string l;
  getline(f, l);
  v[i].puntos = stoi(l);
}

不知道为什么您的示例不起作用,但我不喜欢将 getline 与 &gt;&gt; 混合使用。
你也忘了包括string

【讨论】:

  • 如果我错了,请纠正我,但 getline 返回一个字符串,“puntos”是一个 int。
  • @Franchojavilondo 您将这一行读入一个字符串,然后用stoi 解析该字符串以获得它所代表的整数
  • 是的,这也是一个可行的解决方案
猜你喜欢
  • 2019-06-16
  • 2021-09-01
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
相关资源
最近更新 更多