I'm using fstream to read words from a file and I can't just read the whole word like so:

ifstream ob("file.txt");

    string word;

    ob >> word;

But I need to somehow specify to read 20 positions, even though there might be just spaces included. So I was trying to do something like this:

ifstream ob("file.txt");

    char word[20];

    ob.read(word, 20);

but when I cout this everything seem to be normal except the last element (word[20]) is some kind of a weird symbol, here's an example of what I mean:


5 Years
Discussion Span
Last Post by vijayan121

By dropping down a level, you need to handle lower level concerns like string termination:

ob.read(word, sizeof word - 1);
word[ob.gcount()] = '\0';

Edited by deceptikon


Read 20 chars into a std::string:

#include <fstream>
#include <string>

int main()
    std::ifstream file( "file.txt" ) ;
    std::string str ;
    enum { NCHARS = 20 } ;

    // read upto NCHARS chars into str
    str.reserve(NCHARS) ; // not essential
    file >> std::noskipws ; // do not skip white space on formatted char input
    char c ;
    while( ( file >> c ) && ( str.size() < NCHARS ) ) str += c ;

    // use str
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.