Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Using ifstream with getline();

Check this program

ifstream filein("Hey.txt");
filein.getline(line,99);
cout<<line<<endl;
filein.getline(line,99);
cout<<line<<endl;
filein.close();

The file Hey.txt has alot of characters in it. Well over a 1000

But my question is Why in the second time i try to print line. It doesnt get print?

like image 852
Mohamed Ahmed Nabil Avatar asked Aug 26 '12 19:08

Mohamed Ahmed Nabil


People also ask

What does getline () do in C++?

The C++ getline() is an in-built function defined in the <string. h> header file that allows accepting and reading single and multiple line strings from the input stream. In C++, the cin object also allows input from the user, but not multi-word or multi-line input.

Does Getline work with INT C++?

getline reads an entire line as a string. You'll still have to convert it into an int: std::string line; if ( ! std::getline( std::cin, line ) ) { // Error reading number of questions... }

How do I use Getline with delimiter?

Using std::getline() in C++ to split the input using delimiters. We can also use the delim argument to make the getline function split the input in terms of a delimiter character. By default, the delimiter is \n (newline). We can change this to make getline() split the input based on other characters too!


2 Answers

The idiomatic way to read lines from a stream is this:

std::ifstream filein("Hey.txt");

for (std::string line; std::getline(filein, line); ) 
{
    std::cout << line << std::endl;
}

Notes:

  • No close(). C++ takes care of resource management for you when used idiomatically.

  • Use the free std::getline, not the stream member function.

like image 182
Kerrek SB Avatar answered Oct 05 '22 10:10

Kerrek SB


According to the C++ reference (here) getline sets the ios::fail when count-1 characters have been extracted. You would have to call filein.clear(); in between the getline() calls.

like image 35
Roman Kutlak Avatar answered Oct 05 '22 10:10

Roman Kutlak