简体   繁体   English

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

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

I'm a C++ rookie and am having a little trouble completing an assignment, and my teacher is not going to be available for the next week, so I'm stuck for help! 我是C ++新手,在完成作业时遇到了一些麻烦,下周我的老师将无法上班,所以我一直在寻求帮助! I'm sure I'm just tired and am missing something small, but I'm having trouble getting the fstream object to create the file, and then read from it to print to the screen, everything else seems to work ok. 我确定我只是累了并且缺少一些小东西,但是我无法让fstream对象创建文件,然后从中读取并打印到屏幕上,其他所有工作似乎都正常。

Here are the instructions for the assignment, pretty straightforward and basic: 这是分配的说明,非常简单和基本:

1 - Write a program that will calculate the Area and Circumference of circles. 1-编写一个程序来计算圆的面积和周长。

2 - From main input the radii of the circles via the keyboard and store in an array. 2-从主输入端通过键盘输入圆的半径并存储在数组中。 This must be done via a Loop. 这必须通过循环来完成。 Assume a maximum of 100 records. 假设最多100条记录。

3 - Call a function to calculate the circumference of each circle using the radii above and store in another array. 3-调用函数以使用上方的半径计算每个圆的周长并将其存储在另一个数组中。

4 - Call another function to calculate the area of the circle and store in another array. 4-调用另一个函数来计算圆的面积并存储在另一个数组中。

5 - From main Print to screen the radius, circumference and area of the circles. 5-从主打印到屏幕的半径,圆周和面积。 This information should be printed from the data in the 3 arrays. 此信息应从3个阵列中的数据中打印出来。 Before printing the actual data, print labels for "Radius", "Circumference" and "Area" and align the information under each label. 在打印实际数据之前,请打印“半径”,“周长”和“区域”的标签,并在每个标签下对齐信息。

6 - In main create a fstream object for an output file called Lecture20Output.txt. 6-在main中为名为Lecture20Output.txt的输出文件创建fstream对象。

7 - Call a function to write the radius, circumference and area in the arrays above to Lab20Output.txt 7-调用函数以将上述数组中的半径,周长和面积写入Lab20Output.txt

8 - From main Print to screen the contents of Lab20Output.txt. 8-从主打印屏幕显示Lab20Output.txt的内容。

9 - Sample Run: Radius 5, 4, 7. 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;
}

Just rewind your stream before you try to print. 在尝试打印之前,只需倒回流。

myFile.seekg(0, myFile.beg);  // <---

while (getline(myFile, line))
{
    cout << line << '\n';
}

I'm going to take a stab that this is what you're trying to do: 我要刺一下,这就是您要执行的操作:

// 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;

This always truncates the output file, writes, closes, then opens in read-mode. 这始终会截断输出文件,进行写入,关闭然后以读取模式打开。 It is hard saying for sure this is what you're hoping for based on the question, but it seems to do what you appear to want. 很难确定这是您根据问题希望得到的结果,但是它似乎可以满足您的要求。

Output 输出量

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