【问题标题】:Printing a text file (C++)打印文本文件 (C++)
【发布时间】:2014-02-23 07:20:55
【问题描述】:

我在打印文本文件时遇到问题,这是我必须打印的内容

Michael 33 76 81
Brenda 44 79 90
Alex 79 88 70
Brian 82 93 50
Kevin 77 73 80

这是我的程序

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
struct STUDENT
{
    string   name;
    int      Exam1;
    int      Exam2;
    int      Exam3;
};
STUDENT S[5];
int main()
{
    ifstream f;
    f.open("data.txt");
    for(int i=0;i<5;++i)
    {
        f.getline(S[i].name,5,'\n');
        f>>S[i].Exam1>>S[i].Exam2>>S[i].Exam3;
        cout<<S[i].Exam1<<S[i].Exam2<<S[i].Exam3<<endl;

    }
    f.close();

    system("pause");
    return 0;
}

当我运行我的程序时,它只打印一行零

【问题讨论】:

  • 在我看来,您好像忘记读取名称...假设输入文件看起来像您希望输出看起来一样(您没有说...)
  • 是的,我希望我的输入和输出看起来一样
  • 我仍然得到同样的东西 000 000 000 000 000 按任意键继续。 . .
  • 好的——看我的回答。您的getline 声明不正确。

标签: file text printing


【解决方案1】:

您需要对读取名称的方式稍作改动 - 您需要记住打印它以及空格!

for(int i=0;i<5;++i)
{
    getline(f, S[i].name, ' ');  // <<<< only read up to the space, not the end of line
    f>>S[i].Exam1>>S[i].Exam2>>S[i].Exam3;
    cout<<S[i].name<<" "<<S[i].Exam1<<" "<<S[i].Exam2<<" "<<S[i].Exam3<<endl;

}

我的整个程序:

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
struct STUDENT
{
    string   name;
    int      Exam1;
    int      Exam2;
    int      Exam3;
};
STUDENT S[5];
int main()
{
    ifstream f;
    string buf;
    f.open("data.txt");
    for(int i=0;i<5;++i)
    {
        getline(f, S[i].name, ' ');
        f>>S[i].Exam1>>S[i].Exam2>>S[i].Exam3;
        cout<<S[i].name<<" "<<S[i].Exam1<<" "<<S[i].Exam2<<" "<<S[i].Exam3<<endl;

    }
    f.close();

    system("pause");
    return 0;
}

带输入文件data.txt:

Michael 33 76 81
Brenda 44 79 90
Alex 79 88 70
Brian 82 93 50
Kevin 77 73 80

g++编译,输出结果

Michael 33 76 81

Brenda 44 79 90

Alex 79 88 70

Brian 82 93 50

Kevin 77 73 80
sh: pause: command not found

我不明白你为什么不这样做,除非你没有正确复制我的代码示例......

【讨论】:

  • 仍然得到相同的东西 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 按任意键继续。 . .
  • @user3326689 - 很高兴你成功了。最后解决了什么问题?
  • 我的文本文件实际上有问题,这就是它只打印零的原因。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多