Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from file in c++ till end of line?

Tags:

c++

file

line

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

like image 788
user3050163 Avatar asked Jan 24 '14 13:01

user3050163


People also ask

How do you end a line in C?

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'.

How do you read in a line from a file C?

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.

Does fgets read line by line?

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 do you check if you are at the end of a line in C?

“how to check end of line in c” Code Answer EOF) { printf("%d",n); //other operations with n.. }


1 Answers

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?.

like image 67
herohuyongtao Avatar answered Oct 21 '22 22:10

herohuyongtao