简体   繁体   中英

How to read a specific amount of characters

I can get the characters from console with this code: Displays 2 characters each time in a new line

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main()
{
    char ch[3] = "";

    ifstream file("example.txt");

    while (file.read(ch, sizeof(ch)-1))
    {
       cout << ch << endl;
    }

    return 0;
}

My problem is, if the set of characters be odd it doesn't displays the last character in the text file!

my text file contains this: abcdefg

it doesn't displays the letter g in the console its displaying this:

  • ab
  • cd
  • ef

I wanna display like this:

  • ab
  • cd
  • ef
  • g

I wanna use this to read 1000 characters at a time for a large file so i don't wanna read character by character, It takes a lot of time, but it has a problem if u can fix it or have a better suggestion, share it with me

The following piece of code should work:

while (file) {
    file.read(ch, sizeof(ch) - 1);
    int number_read_chars = file.gcount();
    // print chars here ...
}

By moving the read call into the loop, you'll be able to handle the last call, where too few characters are available. The gcount method will provide you with the information how many characters were actually read by the last unformatted input operation, eg read .

Please note, when reading less than sizeof(ch) chars, you manually have to insert a NUL character at the position returned by gcount , if you intend to use the buffer as a C string, as those are null terminated:

ch[file.gcount()] = '\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