Fstream ifstream I do not understand how to load a data file into my program

My professor is very smart, but expects complete noobs, like me, to just know how to program . I do not understand how the fstream function works.

I will have a data file with three columns of data. I will need to determine with a logarithm whether each row of data will be a circle, rectangle or triangle - this part is simple. I do not understand how the fstream function works.

I think that i:

 #include < fstream > 

then should i declare my file file?

 ifstream Holes; 

then I open it:

 ifstream.open Holes; // ? 

I do not know what the correct syntax is, and I cannot find a simple tutorial. Everything seems more advanced than my skills can handle.

Also, as soon as I read in the data file, what is the correct syntax for placing data in arrays?

I just declare an array, for example. T[N] and cin the fstream Holes object into it?

+4
source share
2 answers

Basic ifstream use:

 #include <fstream> // for std::ifstream #include <iostream> // for std::cout #include <string> // for std::string and std::getline int main() { std::ifstream infile("thefile.txt"); // construct object and open file std::string line; if (!infile) { std::cerr << "Error opening file!\n"; return 1; } while (std::getline(infile, line)) { std::cout << "The file said, '" << line << "'.\n"; } } 

Let’s go further and suppose that we want to process each line according to some pattern. To do this, we use string streams:

 #include <sstream> // for std::istringstream // ... as before while (std::getline(infile, line)) { std::istringstream iss(line); double a, b, c; if (!(iss >> a >> b >> c)) { std::cerr << "Invalid line, skipping.\n"; continue; } std::cout << "We obtained three values [" << a << ", " << b << ", " << c << "].\n"; } 
+10
source

Let me go through each part of the file reading.

 #include <fstream> // this imports the library that includes both ifstream (input file stream), and ofstream (output file stream ifstream Holes; // this sets up a variable named Holes of type ifstream (input file stream) Holes.open("myFile.txt"); // this opens the file myFile.txt and you can now access the data with the variable Holes string input;// variable to hold input data Holes>>input; //You can now use the variable Holes much like you use the variable cin. Holes.close();// close the file when you are done 

Please note that this example does not deal with error detection.

+1
source

Source: https://habr.com/ru/post/1382934/


All Articles