Search code examples
c++stringseekg

(C++) Seekg in fstream cutting off characters


So I'm not entirely sure why this is happening. I've tried just adding in spaces before the words in the txt file that I'm reading from and it fixes it for some, but not all. Basically I'm just trying to return a name, and each name in the file is on a different line. But when i print the names, some of them are cut off, like "Dillon" would be "llon" or "Stephanie" will be "phanie" and so on. Here's the use of seekg:

string Employee::randomFirstName()
{
    int i;
    string fName;

    i = rand() % 100;

    ifstream firstName;
    firstName.open("First Names.txt", ios::out); 
    firstName.seekg(i);
    firstName >> fName;

    return fName;

}

So, I would post the txt file, but its just a list of names, one per line, 100 of them. I've tried looking up examples of the use of seekg, but I cant seem to figure out why it cuts off some. Also, it only cuts off sometimes. One output it'll print out "Dillon" right, next it would print "llon".

Any help would be appreciated


Solution

  • istream::seekg() will move to a character position. Therefore, seeking to a random character position between 0 and 99 (rand() % 100) may end up in the middle of a line. There is no way for seekg to know you wanted to seek to a line number: it has no concept of lines.

    You can instead use std::getline for i number of times to get to that specific line.