简体   繁体   中英

istream::getline() not getting the last character?

I'm trying to get a full sentence from a file into a character buffer to manipulate further in the program. Using the function getline of istream works perfectly fine until I encounter a sentence ending with "...".

Here is an exemple:

C'est normal, vous venez de me demander ma main...

I get the input using this code:

ifstream Historique;
char buff_char[50];
// other stuff
Historique.getline(buff_char, 50, '\n');

What I'm getting:

C'est normal, vous venez de me demander ma main..

And afterwards, I'm trying to do another getline in the files but it fails and I only get an empty character "" in my buffer. I know getline is getting n-1 characters, but I'm telling it where to stop and it works with every other sentence that has only one final punctuation.

Any idea what could be the problem and how to fix it?

getline(buff_char, 50, '\n');

Limits the "get" to 50 characters (null-termination included).

C'est normal, vous venez de me demander ma main...

Is too long.

If wish to use the array buffer, you will need to make it bigger (at least by 1).

The non-member "string" version of getline is an alternative as well;

ifstream Historique;
// ...
std::string line;
std::getline(Historique, line, '\n');

Your string

C'est normal, vous venez de me demander ma main...
123456789|123456789|123456789|123456789|123456789|

is 50 characters long, but C strings require N+1 characters because they have to store a 'nul terminator' - a byte with a value of 0 that lets C functions know where the string ends.

So you either need to increase your buffer size to 51 bytes or you may want to consider using a C++ std::string

#include <string>
// ...
ifstream Historique;
std::string buffer;
// other stuff
getline(Historique, buffer, '\n');

增加数组buff_char的大小

char数组的最后一个字符始终为\\0 ,因此将数组大小设置为所需大小的一倍以上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM