How can I read floats from a .txt file. Depending on the name at the begining of each line I want to read a different number of coordinates. The floats are seperated by "space".
Example: triangle 1.2 -2.4 3.0
The result should be :
float x = 1.2 / float y = -2.4 / float z = 3.0
The file has more lines with differens shapes which can be more complex but I think if i know how to do one of them I can do the others on my own.
My Code so far:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
ifstream source; // build a read-Stream
source.open("text.txt", ios_base::in); // open data
if (!source) { // if it does not work
cerr << "Can't open Data!\n";
}
else { // if it worked
char c;
source.get(c); // get first character
if(c == 't'){ // if c is 't' read in 3 floats
float x;
float y;
float z;
while(c != ' '){ // go to the next space
source.get(c);
}
//TO DO ?????? // but now I don't know how to read the floats
}
else if(c == 'r'){ // only two floats needed
float x;
float y;
while(c != ' '){ // go to the next space
source.get(c);
}
//TO DO ??????
}
else if(c == 'p'){ // only one float needed
float x;
while(c != ' '){ // go to the next space
source.get(c);
}
//TODO ???????
}
else{
cerr << "Unknown shape!\n";
}
}
return 0;
}
To read from a text fileUse the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.
To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.
Why not just use C++ streams the usual way instead of all this getc
madness:
#include <sstream>
#include <string>
for(std::string line; std::getline(source, line); ) //read stream line by line
{
std::istringstream in(line); //make a stream for the line itself
std::string type;
in >> type; //and read the first whitespace-separated token
if(type == "triangle") //and check its value
{
float x, y, z;
in >> x >> y >> z; //now read the whitespace-separated floats
}
else if(...)
...
else
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With