简体   繁体   中英

How to read a specific amount 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 whole line. This worked on another language but doesn't work in C++ for some reason.

You can use read() to specify 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.

This worked on another language but doesn't work in C++ for some reason.

Some things change from language to language. In particular, in this case you've run afoul of the fact that in C++ pointers and arrays are scarcely different. That array gets passed to operator>> as a pointer to char, which is interpreted as a string pointer, so it does what it does to char buffers (to wit read until the width limit or end of line, whichever comes first). Your program ought to be crashing when that happens, since you're overflowing your buffer.

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

Extracts characters from the stream and stores them as a c-string into the array beginning at s. Characters are extracted until either (n - 1) characters have been extracted or the delimiting character '\\n' is found. The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation. If the delimiting character is found, it is not extracted from the input sequence and remains as the next character to be extracted. Use getline if you want this character to be extracted (and discarded). The ending null character that signals the end of a c-string is automatically appended at the end of the content stored in s.

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