How can i read data untill end of 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 the data from the lines and it need to be Int ,not char
In most C compilers, including ours, the newline escape sequence '\n' yields an ASCII line feed character. The C escape sequence for a carriage return is '\r'.
The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be. You can find all the code examples and the input file at the GitHub repo for this article.
The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first.
“how to check end of line in c” Code Answer EOF) { printf("%d",n); //other operations with n.. }
Don't use while(!file.eof())
as eof()
will only be set after reading the end of the file. It does not indicate, that the next read will be the end of the file. You can use while(getline(...))
instead 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 wrong?.
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