1

I am learning to read and write file in C++ and find a problem.

My test.txt file contains 3 string in 3 lines:

abc
def
mnp

My problem is: I don't understand why I need to use f.seekg(2, ios::cur); instead of f.seekg(1, ios::cur); I know how to use seekg() in c++ and I think that I just need to ignore 1 byte to get the next line by the getline() function.

This is my code:

ifstream f;
    f.open("D:\\test.txt", ios::in);
    string str1, str2, str3;
    f >> str1;
    f.seekg(2, ios::cur);
    getline(f, str2);
    getline(f, str3);
    cout << str1 << " " << str2 << " " << str3 << endl;

1 Answers1

1

Reason for your trouble is explained for example here:
Why does std::getline() skip input after a formatted extraction?

However about your actual question about seekg. You open the file in text mode. This means that when you read the file, line feeds are given to your C++ code as single characters, '\n'. But on the disk they may be something else, and it seems you are running your code on Windows. There newline in a text file is typically two bytes, CR (ASCII code 13) and LF (ASCII code 10). Reading or writing in text mode will perform this conversion between a single character in your C++ string vs two bytes in the file for you.

seekg works on offsets and does not care about this, offsets are same whether you open the file in text or binary mode. If you use seekg to skip new line, your code becomes platform-dependent, on Windows you need to skip 2 bytes as explained above, while in other platforms such as Unix you need to skip just single byte.

So, do not use seekg for this purpose, see the linked question for better solutions.

hyde
  • 50,653
  • 19
  • 110
  • 158
  • Thanks for your answer. It's so useful!! – babylearnmaths Jul 04 '20 at 14:59
  • @babylearnmaths No problem. Note that usual way to say "thank you" here is to upvote the answer. Also, when/if you get a satisfactory answer to your question, it's good to accept the answer you like best (but it's a good idea to wait 24 hours if you want all timezones to have a chance of seeing and answering your question). – hyde Jul 04 '20 at 18:42