0
對不起,如果標題不清楚,我遇到的問題是我必須導入一個複雜的數字文本文件,其中一些然而沒有虛構或真實的部分,我不知道如何只輸出想像或真正的部分,如果其他人失蹤。只有在某個特定情況下,我如何才能輸出某個對象的某個部分?
這裏是我的代碼:
的.h頭文件:
#ifndef COMPLEXOBJ_H
#define COMPLEXOBJ_H
#include <iostream>
class complexType
{
friend std::ostream& operator<<(std::ostream& os, const complexType& obj);
friend double getreal(const complexType& sample1);
friend char getsign(const complexType& sample2);
public:
complexType();
complexType(double r, double i, char signin);
double getreal() const;
private:
double real;
double imagine;
char sign;
};
#endif // COMPLEXOBJ_H
的.cpp類文件:
#include "Complexobj.h"
#include <iostream>
using namespace std;
complexType::complexType()
{
real=0;
imagine=0;
sign= '+';
}
complexType::complexType(double r, double i, char signin)
{
real=r;
imagine=i;
sign=signin;
}
ostream& operator<<(ostream& os, const complexType& obj)
{
os << obj.real<< obj.sign << obj.imagine << "i";
return os;
}
double complexType::getreal() const
{
return real;
}
CPP主文件:
#include "Complexobj.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
void sorter(complexType[], int countin);
int main()
{
ofstream outputfile;
ifstream inputfile;
string str;
double realpart;
double imaginarypart;
int symbol;
char ch;
string strone;
string strtwo;
complexType storage[100];
int counter = 0;
inputfile.open("126import.txt");
if(inputfile.fail())
{
cout << "File opening failed." << endl;
exit(1);
}
outputfile.open("126export.txt");
inputfile >> str;
while(inputfile)
{
char firstch = '+';
if(str.at(0) == '-')
{
str = str.substr(1,str.length() - 1);
firstch = '-';
}
symbol=str.find("+");
ch = '+';
if(symbol < 0)
{
symbol = str.find("-");
ch = '-';
}
stringstream streamin(str);
getline(streamin, strone, ch);
getline(streamin, strtwo, 'i');
realpart= atof(strone.c_str());
imaginarypart= atof(strtwo.c_str());
if(ch == '-')
realpart *= -1;
complexType outpobj(realpart, imaginarypart, ch);
storage[counter]=outpobj;
counter++;
inputfile >> str;
}
sorter(storage, counter);
for(int u=0; u<counter;u++)
{
outputfile << "Object " << u+1 << ": " << storage[u] << endl;
}
inputfile.close();
outputfile.close();
return 0;
}
void sorter(complexType storarray[], int countin)
{
complexType temp;
for(int k=1; k<countin;k++)
{
for(int j=0;j<countin-k;j++)
{
if(storarray[j].getreal() > storarray[j+1].getreal())
{
temp=storarray[j];
storarray[j]=storarray[j+1];
storarray[j+1] = temp;
}
}
}
}
對於大部分代碼工作,但我的英寸放文件是:
1+1i
2+2i
3.3+3.4i
4.4-4.5i
-5.5-5.6i
-6
7i
-8i
而不是將其導出其正確出口:
Object 1: -8-5.6i
Object 2: -7-5.6i
Object 3: -6-5.6i
Object 4: -5.5-5.6i
Object 5: -4.4-4.5i
Object 6: 1+1i
Object 7: 2+2i
Object 8: 3.3+3.4i
與5.6我的起步,因爲它不知道如何它們分開
我知道問題是我的輸出過載,或者當我的主讀入複雜的對象,但我不知道如何解決它。