0

Would you please help me with this assignment.

I am supposed to create a txt file that contains ID and mark for three students and the output should be the ID and a message in a different txt file.

When I try running the code, the output txt file is blank. I tried changing the code so the program outputs results on screen, but for some reason it doesn't read the first line and it repeats the third!

I'm using Visual studio 2012.

input data:

20112233    90
20115566    80
20113756    70

Here is my code:

#include <iostream>
#include <fstream>
using namespace std;
void main ()
{

    int ID, mark, c=1;

    ifstream fin;
    fin.open ("marks.txt");
    fin >> ID >> mark;

    ofstream fout;
    fout.open ("grades");

    while (c<=3)
    {   

    fin >> ID >> mark;

    if (mark >= 90 && mark <= 100) {
            fout << ID << "\t" << "Excellent" << endl;
    c++;
    }
    else if (mark >= 80 && mark <= 89) {
            fout << ID << "\t" << "Very Good" << endl;
        c++;
    }

    else if (mark >= 70 && mark <= 79) {
            fout << ID << "\t" << "Good" << endl;
    c++;
    }

        else  if (mark >= 60 && mark <= 69) {
            fout << ID << "\t" << "Accepted" << endl;
        c++;
        }

        else if (mark >= 0 && mark <= 59) {
            fout << ID << "\t" << "Fail" << endl;
        c++;
        }

        else fout << "Wrong data";

    }


    fin.close ();
    fout.close ();

    system ("PAUSE");

}
4

2 回答 2

1

让我们来看看这些步骤:

  1. 打开.txt文件进行输入:

    std::ifstream fin("marks.txt");
    

    请注意我们如何使用构造函数来打开 .txt 文件,而不是使用open. 这是在构建时已知路径时打开 .txt 文件的首选方法。

  2. 打开.txt文件进行输出:

    std::ofstream fout("grade");
    
  3. 创建要从输入 txt 文件中提取其值的变量。那将是 ID 和等级:

    int ID, mark;
    
  4. 现在,从 txt 文件中提取值非常简单。如果要提取 txt 文件中存在的每一行的值,则无需设置计数器 - 当提取到达 EOF 字符(文件结尾)时,提取将停止。

    提取的惯用方法是使用循环的条件表达式执行提取,以便它可以返回流,从而可以评估有效的文件条件。这是通过 IOStreams 中格式化和未格式化的 I/O 运算符自动完成的:

    while (fin >> ID >> mark)
    {
        // ...
    }
    
  5. 关闭文件:这是通过销毁流类本身自动完成的。如果您不再使用这些文件,只需让它们在超出范围或程序结束时自行关闭。意思是不要打电话close()

于 2013-11-03T18:58:27.173 回答
1

首先main函数必须返回一个int.

其次,您似乎从流中执行读取并将其丢弃。

fin >> ID >> mark; // Read tokens and clear them from the stream.

第三,您不检查是否以及从流中读取的内容。

while (c<=3)
{   

fin >> ID >> mark; // What if this fails?

尝试这样的事情:

#include <fstream>

int main () {
    std::ifstream fin("marks.txt");
    std::ofstream fout("grades");

    int id, mark;
    while (fin >> id >> mark) { // Loop while tokens can be read successfully
        if (mark >= 90 && mark <= 100) {
            fout << id << "\tExcellent" << std::endl;
        } else if (mark >= 80 && mark <= 89) {
            fout << id << "\tVery Good" << std::endl;
        } else if (mark >= 70 && mark <= 79) {
            fout << id << "\tGood" << std::endl;
        } /* ... */
    }
}
于 2013-11-03T18:58:37.777 回答