繁体   English   中英

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

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

我是C ++新手,在完成作业时遇到了一些麻烦,下周我的老师将无法上班,所以我一直在寻求帮助! 我确定我只是累了并且缺少一些小东西,但是我无法让fstream对象创建文件,然后从中读取并打印到屏幕上,其他所有工作似乎都正常。

这是分配的说明,非常简单和基本:

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

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

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

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

5-从主打印到屏幕的半径,圆周和面积。 此信息应从3个阵列中的数据中打印出来。 在打印实际数据之前,请打印“半径”,“周长”和“区域”的标签,并在每个标签下对齐信息。

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!    
========================

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM