我有一個問題,我的程序基本上是一個簡單的數學程序。它做了一些向量乘法和向量矩陣乘法,它工作正常,直到我嘗試從文本中讀取數據。我可以編譯該程序,但是當我嘗試執行它時,出現錯誤:「Dataname.exe不起作用」。 這是我的代碼。不考慮cins和couts如何使用ifstream
#include<iostream>
#include<cmath>
#include<vector>
#include"header.hpp"
#include<fstream>
using namespace std;
int main()
{
ifstream einlesen ("Zahlen.dat"); //function "einlesen" opens the file "Zahlen.dat".
if (einlesen) // Message if the file has been opend
cout<<"Daten wurden eingelesen"<<endl;
else {
cout<<"Konnte Daten nicht einlesen"<<endl;
return 99;
}
double a;
int n{0};
while (einlesen >>a>>a>>a>>a>>a>>a>>a) n++;//Loop copys datas on a
einlesen.clear();//stops the loop after the last data is copied.
einlesen.seekg(0, ios_base::beg);//??
vector<double> vecein(n), vecein1(n),Matrixein(n);
for (a = 0;a<n;a++);//copys datas to a vector further calculations
{
einlesen>>vecein.at(a);
einlesen>>vecein1.at(a);
einlesen>>Matrixein.at(a);
}
double Matrix1[9]; //defining my Matrix and the coordinates of my vectors.
double x,y,z,x_1,x_2,x_3;
vector<double> vec(3);
vector<double> vec1(3);
// Old code where I read the data with `cin`:
/*cout<<"Geben Sie die x Koordinaten ein:"<<endl;
cin>>vec[0];
cin>>vec1[0];
cout<<"Geben Sie die y Koordinaten ein:"<<endl;
cin>>vec[1];
cin>>vec1[1];
cout<<"Geben Sie die z Koordinaten ein:"<<endl;
cin>>vec[2];
cin>>vec1[2];
cout<<"Geben Sie eine Matrix ein"<<endl;
cin>>Matrix1[0]>>Matrix1[1]>>Matrix1[2]>>Matrix1[3]>>Matrix1[4]>>Matrix1[5]>>Matrix1[6]>>Matrix1[7]>>Matrix1[8];
cout<<"Vektor1:<"<<vec[0]<<","<<vec[1]<<","<<vec[2]<<">"<<endl;
cout<<"Vektor2:<"<<vec1[0]<<","<<vec1[1]<<","<<vec1[2]<<">"<<endl;
vector<double> Addition(3);
Addition = Vektoraddition(vec,vec1);
cout<<"Addition:"<<"<"<<Addition[0]<<","<<Addition[1]<<","<<Addition[2]<<">"<<endl;
double Skalarprodukt;
Skalarprodukt = Skalarpr(vec,vec1);
cout<<"Skalarprodukt:"<<Skalarprodukt<<endl;
vector<double> kreuzprodukt(3);
kreuzprodukt = Kreuzprodukt (vec,vec1);
cout<<"Kreuzprodukt:"<<"<"<<kreuzprodukt[0]<<","<<kreuzprodukt[1]<<","<<kreuzprodukt[2]<<">"<<endl;
vector<double> MatrixVektor(3);
MatrixVektor = Matrix_vektor (Matrix1, vec);
cout<<"Matrix*Vektor:"<<"<"<<MatrixVektor[0]<<","<<MatrixVektor[1]<<","<<MatrixVektor[2]<<">"<<endl;*/
ofstream ausgabe ("Ausgabe.dat");//write the data on Ausgabe.dat
for (int i = 0; i < a; i++)
{
ausgabe << "(" << vecein[i] << "," << vecein1[i] << "," << Matrixein[i]<<")" << endl;
}
return 0;
}
它是用德語寫的,所以我不會對變量名感到疑惑。我的問題是,我不太明白我在while循環中做什麼。 Zahlen.dat是一個類似於1 2 3 4 5 6 7的文件...而Ausgabe.dat是一個空文件。實際上它的確在Ausgabe.dat中寫入,因爲它告訴我內容已經改變,但是當我重新加載文件時它仍然是空的。
您可以嘗試縮進並更清晰地格式化您的代碼嗎?並用它出現在源代碼中的相同語言報告錯誤消息,以便我們可以知道哪一行拋出錯誤? – Davislor
如果輸入文件沒有打開,並且你不能說出原因,一種技術是在程序的頂部「#include'和'#include ',然後,在錯誤信息是'cerr << __FILE__ <<':'<< __LINE__ <<「:」<< strerror(errno)<< endl;'代替。我的大部分程序都有一個類似的宏。 –
Davislor