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:

click

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';

Dudes ...use getline and put . As delimiter

Dudes ...use getline and put . As delimiter

How does '.' as a delimiter enforce field widths of 20 characters?

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
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.