In C++ möchte ich eine Textdatei mit Spalten von Floats lesen und sie in einem 2D-Array.C++ lesen Float-Werte von. TXT und legte sie in eine unbekannte Größe 2D-Array
Erste Zeile wird die 1. Spalte und so weiter.
Die Größe des Arrays ist unbekannt, es hängt von den Zeilen und Spalten ab, die variieren können.
Ich habe versucht mit "getline", "inFile >>", aber alle Änderungen, die ich gemacht habe, haben einige Probleme.
Zum Beispiel Gibt es eine Möglichkeit, die unnötigen Zeilen/Zeilen zu entfernen, nachdem die Werte vorhanden sind?
Datei sieht wie folgt aus (+/-):
- Zeichen "\ t" Zeichen "\ t" Zeichen "\ n"
- float "\ t" float "\ t" float " \ t "float" \ n "
- float" \ t "float" \ t "Float" \ t "float" \ n "
- Float" \ t "Float" \ t "float" \ t "float "\ n"
Danke
0 jetztBis ich habe dies:
int ReadFromFile(){
ifstream inFile;
ofstream outFile;
int nLinActual = 0;
const int nCol = 9;
const int nLin = 10;
// open file for reading
inFile.open("values.txt");
// checks if file opened
if(inFile.fail()) {
cout << "error loading .txt file reading" << endl;
return 1;
}
// open file for writing
outFile.open ("outArray.txt");
// checks if file opened
if(outFile.fail()) {
cout << "error loading .txt file for writing" << endl;
return 1;
}
// Doesn't read the first line
string dummyLine, dummyLine2, dummyLine3;
getline(inFile, dummyLine);
// Declares Array
float values[nLin][nCol];
//Fill Array with -1
for(int l=0; l<nLin; l++)
for(int c=0; c<nCol; c++)
values[l][c] = -1;
// reads file to end of *file*, not line
while(!inFile.eof()) {
for (int i=0; i<nCol; i++) {
inFile >> values[i][nLinActual];
}
i=0;
++nLinActual;
}
// Check what's happening
cout << endl;
for(int l=0; l<nLin; l++){
for(int c=0; c<nCol; c++){
cout << values[l][c] << "\t";
outFile << values[l][c] << "\t";
}
cout << endl;
outFile << endl;
}
inFile.close();
outFile.close();
return 0;
}
Am besten, einige Code zu posten und geben Sie mehr Details über die "Probleme", die Sie damit hatten. –
Wie sieht die Datei aus? Kannst du deinen Beitrag bearbeiten? – 0x499602D2
Mein Code funktioniert jetzt, siehe unten. – 0x499602D2