C++在类函数中和类外写入文件

标签 c++ file class operators overloading

我目前正在做一项作业,我必须对长度不超过 20 位的数字进行加、减和乘。我必须使用类和重载运算符,并且所有输入/输出都必须与屏幕一起写入文件。

我的大部分内容都已完成。将所有内容写入文件才是真正让我卡住的地方。我打开一个文件以读取主函数中的输入,我考虑过将 ofstream 变量传递到我的类函数中,但意识到这是行不通的,因为有几个是二元运算符并且不会进行第三次争论。

这是我的代码: 头文件:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class LargeIntegerNumber
{
public:
    //Default constructor
    LargeIntegerNumber();
    //Set Array calls getNumber and convertNumber
    void setArray(ostream& out);
    //Obtains user input for string
    void getNumber(ostream& out);
    //Parses string into array
    void convertNumber(LargeIntegerNumber array1);
    //Compares the two numbers and displays result
    void comparison(LargeIntegerNumber array1, LargeIntegerNumber array2, ostream& out);

    friend void operator *(LargeIntegerNumber array1, LargeIntegerNumber array2);
    friend void operator -(LargeIntegerNumber array1, LargeIntegerNumber array2);
    friend void operator +(LargeIntegerNumber array1, LargeIntegerNumber array2);
    friend istream& operator >>(istream& cin, LargeIntegerNumber& array1);


private:

    int array[20];
    string number;
    int numSize;
    int arrayNegative;


};

我的实现文件(由于大小,我遗漏了一些东西)

istream& operator >>(istream& cin, LargeIntegerNumber& array1)
    {
    //Prompt user to input string and retrieve result
    cout<<"Please enter a number of up to 20 digits: "<<endl;
    /*out<<"Please enter a number of up to 20 digits: "<<endl;*/

    cin >> array1.number;
    cout<<endl;
    /*out << number;*/
    /*out<<endl;*/
    //Obtain the length of the number 
    array1.numSize = array1.number.length();

    array1.convertNumber(array1);

    return cin;

void LargeIntegerNumber::convertNumber(LargeIntegerNumber array1)
{
    for (int i = 0; i < 20; i++)
        array[i] = 0; 

    arrayNegative = 0;

    for(int i =0; i <  numSize; i++)
    {

        array[i] = number[numSize - i - 1] - 48; // Converting a character into an integer will give the ASCII code of the number, so to extract the actual numbe you have do - 48
        //-3 is ascii code for negative symbol, if detected in string, number is negative
        if (array[i] == -3)
        {
            //Set array is negative flag, then make '-' in string a 0
        arrayNegative = 1;
        array[i] = 0;
        }

    }

    //Detects if string size is too large, takes - symbol into consideration
    if ((numSize == 22) && (arrayNegative == 1))
    {
        cout<<"Number is greater than 20 digits, please try again."<<endl;
        /*out<<"Number is greater than 20 digits, please try again."<<endl;*/
        exit(1);
    }

void operator *(LargeIntegerNumber array1, LargeIntegerNumber array2)
{
    LargeIntegerNumber array3;

    cout<<"Beginning Multiplication Process"<<endl;


// Multiplication
cout<<array1.number<<" * "<<array2.number<< " = ";


if ((array1.arrayNegative == 1) && (array2.arrayNegative == 0) || (array1.arrayNegative == 0) && (array2.arrayNegative == 1))
{
    //If either number is negative, the result will be negative
    cout<<"-";

}
for(int i =0; i< array2.numSize; i++)
{
    for(int j = 0 ; j<array1.numSize; j++)
    {
        int tempNo = array1.array[j] * array2.array [i]; // Multiply each two digits
        if ((i == 19) && (tempNo > 9))
        {
            cout<<endl;
            cout<<"WARNING! THE RESULTS WILL BE GREATER THAN 20 DIGITS! ANSWER WILL BE INCORRECT!"<<endl;
        }
        int a = tempNo % 10; // Find out the result, and remove the carry part
        array3.array[i+j] += a; // Save the result of the multiplication

        a = array3.array[i+j]% 10; // Find out the result
        int c = array3.array[i+j]/ 10; // Find if I have a carry after we add the numbers
        array3.array[i+j] = a;

         int b = tempNo / 10; // find out the carry 
        array3.array[i+j+1] += b+c;     // Add the carry to the next number

        if ((i+j == 19) && (b+c > 9))
        {
            cout<<endl;
            cout<<"WARNING! THE RESULTS WILL BE GREATER THAN 20 DIGITS! ANSWER WILL BE INCORRECT!"<<endl;
        }
    }   
}
//Display results
int i =19;

while ( array3.array[i] ==0)
    i--;

// print out the result without 0s
do{
    cout<<array3.array[i];


    i--;
}while(i >=0);

cout<<endl;

}

    }

还有我的主要内容:

int main()
{
    //Declaration of numbers
    LargeIntegerNumber num1, num2;
    int hold;
    ofstream out;
    string fileName;




    //Open outfile
    out.open("outfile.txt");

    //if file not found
    if (out.fail())
    {
        cout<<"File not found"<<endl;
        exit(1);
    }

    //Menu
    int menu;
    char loop = 'Y';
    do
    {

    cout<<"Please choose from the menu options below (Enter the cooresponding number on the left):"<<endl;
    cout<<"1: Add two numbers"<<endl;
    cout<<"2: Subtract two numbers"<<endl;
    cout<<"3: Multiply two numbers"<<endl;

    out<<"Please choose from the menu options below (Enter the cooresponding number on the left):"<<endl;
    out<<"1: Add two numbers"<<endl;
    out<<"2: Subtract two numbers"<<endl;
    out<<"3: Multiply two numbers"<<endl;
    cin>>menu;
    cout<<endl;
    out<<endl;
    out<<menu;
    out<<endl;




    switch(menu)
    {
        //Addition
    case 1:
    cout<<"You have selected (1) Addition"<<endl;
    out<<"You have selected (1) Addition"<<endl;
    //Obtain both numbers, do arithmetic, display, then compare
    cin >> num1;
    cin >> num2;

    /*num1.setArray(out);
    num2.setArray(out);*/
    num1 + num2;
    num1.comparison(num1, num2, out);
    break;
    //Subtraction
    case 2:
    cout<<"You have selected (2) Subtraction"<<endl;
    out<<"You have selected (2) Subtraction"<<endl;
    cin >> num1;
    cin >> num2;
    /*num1.setArray(out);
    num2.setArray(out);*/
    num1 - num2;
    num1.comparison(num1, num2, out);
    break;
    //Multiplication
    case 3:
    cout<<"You have selected (3) Multiplication"<<endl;
    out<<"You have selected (3) Multiplication"<<endl;
    cin >> num1;
    cin >> num2;
    /*num1.setArray(out);
    num2.setArray(out);*/
    num1 * num2;
    num1.comparison(num1, num2, out);
    break;
    default:
        cout<<"Not a valid menu option, please try again"<<endl;
        out<<"Not a valid menu option, please try again"<<endl;
    }

    cout<<"Would you like to continue? (Enter Y/y for yes)"<<endl;
    out<<"Would you like to continue? (Enter Y/y for yes)"<<endl;
    cin>>loop;
    out<<loop;
    cout<<endl;
    out<<endl;
    }while ((loop == 'Y') || (loop == 'y'));
    //Close file
    out.close();

}

大部分内容只是为了向您展示我的工作成果。我的所有代码在大多数情况下都运行良好,我只是不确定如何将我的 ofstream 变量从 main 转换为我的二元运算符,因为我无法传递它们。

我的一个想法是让所有算术运算符都没有 cout 语句(我对类和重载运算符还是新手,通常不建议在重载二元运算符中包含 cin/out 语句吗?)并使所有 cout输出函数中的语句可以接受 ostream 变量作为参数。

编辑:

抱歉,我应该更清楚一点。

我的程序必须将用户在屏幕上看到的所有内容(从输入到输出)写入文件,而不仅仅是结果。

最佳答案

在您的类中使用通用输出或写入方法:

class LargeNumber
{
  public:
    std::ostream& write(std::ostream& out) const;
    // Or you could overload the insertion operator
    friend std::ostream& operator<<(std::ostream& out, const LargeNumber& ln);
}

std::ostream& operator<<(std::ostream& out,
                         const LargeNumber& ln)
{
   out << ln.data_member;
   return out;
}

因为 std::ofstream 继承自 std::ostream 您可以将文件流传递给任一方法。

int main(void)
{
  LargeNumber l; 
  ofstream out("output.txt");
  // strategy 1:
  l.write(out); // Output to file.
  l.write(cout); // output to screen.

  // strategy 2:
  out << l;  // Output to the file.
  cout << l; // Output to the screen.

  return 0;
}

关于C++在类函数中和类外写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24965467/

相关文章:

java - 如何在 Java 中从另一个类创建和构造一个类

python - 在 ipython 中给出 "missing 1 required positional argument"的简单类定义

C++封装,有什么用

c++ - 同步两个线程在彼此之间传递事件

c++ - 使用 std::regex 过滤输入

java - 如何在与 Web 应用程序相同的目录中创建文件夹?

php - 计算在代码中打开的文件大小的最快方法 (PHP)

具有 freeglut 连续重新计算图形闪烁的 C++ OpenGL

c++ - Sprite 的凸多边形化

c# - 确定文件在哪个物理硬盘上?