C++使用fstream对象读取和写入文本文件时出现问题

C++ Trouble reading and writing to text file using the fstream object

本文关键字:文件 文本 问题 fstream 使用 对象 读取 C++      更新时间:2023-10-16

我是一名C++新手,在完成一项作业时遇到了一些困难,我的老师下周都不在,所以我一直在寻求帮助!我确信我只是累了,错过了一些小东西,但我很难让fstream对象创建文件,然后从中读取并打印到屏幕上,其他一切似乎都很好。

以下是任务的说明,非常简单和基本:

1-编写一个程序,计算圆的面积和周长。

2-通过键盘从主输入圆的半径,并存储在阵列中。这必须通过循环来完成。假设最多有100条记录。

3-调用一个函数,使用上面的半径计算每个圆的周长,并存储在另一个数组中。

4-调用另一个函数来计算圆的面积并存储在另一个数组中。

5-从主屏幕打印圆的半径、周长和面积。该信息应根据3个阵列中的数据打印出来。在打印实际数据之前,打印"半径"、"周长"answers"面积"的标签,并将每个标签下的信息对齐。

6-在main中为一个名为Lecture20Output.txt的输出文件创建一个fstream对象。

7-调用一个函数,将上面数组中的半径、周长和面积写入Lab20Output.txt

8-从主打印到屏幕Lab20Output.txt的内容。

9-采样运行:半径5、4、7。

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
// prototypes
void getCircumf(const double, double, double &);
void getArea(const double, double, double &);
void writeOutFile(int, double[], double[], double[], fstream &);
void greeting();
int main()
{
    const int ARRAY_SIZE = 100;
    const double PI = 3.14;
    int i = 0, i2 = 0;
    double radii[ARRAY_SIZE],
           circumf[ARRAY_SIZE],
           area[ARRAY_SIZE];
    fstream myFile;
    string line;
    // use loop to prompt user for radii
    cout << "==============================================================" << endl;
    cout << "  Below, you may enter all of your radii (up to 100 entries)  " << endl;
    cout << "         *** Enter 0 (zero) when you are finished ***         " << endl;
    cout << "==============================================================" << endl;
    while (i<100)
    {
        cout << "nEnter your radius: ";
        cin >> radii[i];
        if (radii[i] == 0)          // test if user has no more entries
            i = 100;
        else
        {
            getCircumf(PI, radii[i], circumf[i]);   // call function to calculate circumference
            getArea(PI,radii[i], area[i]);          // call function to calculate area
            i++;
            i2++;
        }
    }
    // print results table to screen
    cout << "n======================================="
         << "n| Radius | Circumference |    Area    |"
         << "n=======================================" << endl;
    for (int i=0; i<i2; i++)
    {
        cout << fixed << setprecision(2);
        cout << "| "
             << setw(6) << radii[i]
             << " | "
             << setw(13) << circumf[i]
             << " | "
             << setw(10) << area[i]
             << " |" << endl;
        cout << "---------------------------------------" << endl;
    }
    // call function to print results table to output file
    myFile.open("Lab20Output.txt", ios::out | ios::in);
    if (!myFile)
    {
        cout << "FILE OPEN ERROR!" << endl;
        return 0;
    }
    cout << "nWe are now writing this data to a file...";
    writeOutFile(i2,radii,circumf,area,myFile);
    cout << "done." << endl;
    // print to screen the contents of file "Lab20Output.txt"
    cout << "nNow we will read back the data from the file..." << endl;
    while (getline(myFile, line))
    {
        cout << line << 'n';
    }
    myFile.close();
    greeting();
    return 0;
}
// function definitions
void getCircumf(const double PI, double radii, double &circumf)
{
    // caluculate the circumference of a circle
    circumf = 2 * PI * radii;
}
void getArea(const double PI, double radii, double &area)
{
    // caluculate the area of a circle
    area = PI * (radii * radii);
}
void writeOutFile(int i2, double radii[], double circumf[], double area[], fstream &myFile)
{
    // print results table to myFile
    myFile << "n=======================================n"
           << "| Radius | Circumference |    Area    |n"
           << "=======================================" << endl;
    for (int i=0; i<i2; i++)
    {
        myFile << fixed << setprecision(2);
        myFile << "| "
               << setw(6) << radii[i]
               << " | "
               << setw(13) << circumf[i]
               << " | "
               << setw(10) << area[i]
               << " |" << endl;
        myFile << "---------------------------------------" << endl;
    }
}
void greeting()
{
    cout << "n========================"
         << "n    Have a nice day!    "
         << "n========================" << endl;
}

在尝试打印之前只需倒带流。

myFile.seekg(0, myFile.beg);  // <---
while (getline(myFile, line))
{
    cout << line << 'n';
}

我要尝试一下,这就是你想要做的:

// call function to print results table to output file
// NOTE: open in out/trunc mode.
myFile.open("Lab20Output.txt", ios::out|ios::trunc);
if (!myFile)
{
    cout << "FILE OPEN ERROR!" << endl;
    return 0;
}
cout << "nWe are now writing this data to a file...";
writeOutFile(i2,radii,circumf,area,myFile);
cout << "done." << endl;
myFile.close();
// print to screen the contents of file "Lab20Output.txt"
cout << "nNow we will read back the data from the file..." << endl;
// NOTE: Open in read-mode
myFile.open("Lab20Output.txt", ios::in);
while (getline(myFile, line))
{
    cout << line << 'n';
}
myFile.close();
greeting();
return 0;

这总是截断输出文件,写入、关闭,然后以读取模式打开。根据这个问题,很难说这是你所希望的,但它似乎做到了你想要的。

输出

==============================================================
  Below, you may enter all of your radii (up to 100 entries)  
         *** Enter 0 (zero) when you are finished ***         
==============================================================
Enter your radius: 10
Enter your radius: 11
Enter your radius: 0
=======================================
| Radius | Circumference |    Area    |
=======================================
|  10.00 |         62.80 |     314.00 |
---------------------------------------
|  11.00 |         69.08 |     379.94 |
---------------------------------------
We are now writing this data to a file...done.
Now we will read back the data from the file...
=======================================
| Radius | Circumference |    Area    |
=======================================
|  10.00 |         62.80 |     314.00 |
---------------------------------------
|  11.00 |         69.08 |     379.94 |
---------------------------------------
========================
    Have a nice day!    
========================