【问题标题】:C++ Writing to a file in and out of class functionsC ++在类函数内外写入文件
【发布时间】:2014-07-25 22:29:33
【问题描述】:

我目前正在处理一项作业,我必须对长度不超过 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 变量从主变量转换为我的二进制运算符,因为我无法传递它们。

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

编辑:

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

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

【问题讨论】:

  • array[i] = number[numSize - i - 1] - 48 中你为什么不使用'0' 而不是48?它们是等价的,但使用 '0' 会使该声明更加清晰。
  • 您可以实现一个write 方法,该方法使用std::ostream 并传递std::cout 用于写入屏幕和文件流以写入您的文件。
  • 将运算符和其他函数分开,形成将数字写入文件的函数。实现ostream&amp; operator&lt;&lt;(ostream&amp; out, LargeIntegerNumber const&amp; num) 以将数字写入文件。

标签: c++ file class operators overloading


【解决方案1】:

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

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

【讨论】:

  • edit- 重读我的问题,很抱歉我应该更具体一些,这需要对用户在屏幕上看到的所有内容都有效。结束编辑-我明白你在说什么。我尝试了类似的方法,但它只写入一个变量(在 ln.data_member 中指定的那个)我需要它来处理 cout 语句以及其他变量。
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2012-05-25
相关资源
最近更新 更多