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