Reading from file in C ++ to end of line?

How can I read data to the end of the line? I have a text file "file.txt" with this

1 5 9 2 59 4 6 2 1 2 3 2 30 1 55 

I have this code:

 ifstream file("file.txt",ios::in); while(!file.eof()) { ....//my functions(1) while(?????)//Here i want to write :while (!end of file) { ...//my functions(2) } } 

in my functions (2) I use data from strings and should be Int, not char

+6
source share
4 answers

Do not use while(!file.eof()) , since eof() will only be installed after reading the end of the file. It does not indicate that the end of the file will be the next read. Instead, you can use while(getline(...)) and combine with istringstream to read numbers.

 #include <fstream> #include <sstream> using namespace std; // ... ... ifstream file("file.txt",ios::in); if (file.good()) { string str; while(getline(file, str)) { istringstream ss(str); int num; while(ss >> num) { // ... you now get a number ... } } } 

You need to read. Why is iostream :: eof inside a loop condition considered incorrect? .

+4
source

As for reading to the end of the line. there std::getline .

You have one more problem, and that means that you are executing a while (!file.eof()) , which most likely will not work as you expect. The reason is that the eofbit flag eofbit not set until you try to read from behind the end of the file. Instead, you should do it, for example. while (std::getline(...)) .

+2
source
 char eoln(fstream &stream) // C++ code Return End of Line { if (stream.eof()) return 1; // True end of file long curpos; char ch; curpos = stream.tellp(); // Get current position stream.get(ch); // Get next char stream.clear(); // Fix bug in VC 6.0 stream.seekp(curpos); // Return to prev position if ((int)ch != 10) // if (ch) eq 10 return 0; // False not end of row (line) else // (if have spaces?) stream.get(ch); // Go to next row return 1; // True end of row (line) } // End function 
+1
source

If you want to write it as a function to call somewhere, you can use a vector. This is the function that I use to read such a file and returns integer elements.

 vector<unsigned long long> Hash_file_read(){ int frames_sec = 25; vector<unsigned long long> numbers; ifstream my_file("E:\\Sanduni_projects\\testing\\Hash_file.txt", std::ifstream::binary); if (my_file) { //ifstream file; string line; for (int i = 0; i < frames_sec; i++){ getline(my_file, line); numbers.push_back(stoull(line)); } } else{ cout << "File can not be opened" << endl; } return numbers; } 
0
source

All Articles