How to read a certain number of characters from a text file

I tried to do it like this:

#include <iostream> #include <fstream> using namespace std; int main() { char b[2]; ifstream f("prad.txt"); f>>b ; cout <<b; return 0; } 

It should read 2 characters, but it reads a whole line. This worked in another language, but for some reason does not work in C ++.

+7
source share
3 answers

You can use read() to indicate the number of characters to read:

 char b[3] = ""; ifstream f("prad.txt"); f.read(b, sizeof(b) - 1); // Read one less that sizeof(b) to ensure null cout << b; // terminated for use with cout. 
+8
source

This worked in another language, but does not work in C ++ for some reason.

Some things change from language to language. In particular, in this case, you are faced with the fact that in C ++ pointers and arrays are hardly different from each other. This array is passed to the → operator as a pointer to a char, which is interpreted as a pointer to a string, so it does what it does with char buffers (to read to the limit of the width or end of the string, depending on what happens first). Your program should crash when this happens as you overflow your buffer.

+2
source
 istream& get (char* s, streamsize n ); 

Extracts characters from a stream and saves them as a c-string into an array starting with s. Characters are retrieved until (n - 1), or the delimiter character '\ n' is equal to the one found. Extraction also stops if the end of the file is reached in the input sequence or if an error occurs during the input operation. If a delimiting character is found, it is not extracted from the input and remains as the next character to be extracted. use getline if you want this character to be extracted (and discarded). The trailing null character that signals the end of the c-string equal to is automatically added to the end of the contents stored in s.

0
source

All Articles