0

I have a homework assignment and using strings is forbidden so I need to use char[] arays. My problem involves reading the first 150 characters (or until the end of the line, if it contains less than 150 characters) for every line in a text file. However, the function getline() gives the content of the line to a string, not a char[] array. I lookep up the internet and couldn't find a function, the parameter of which is an array. I tried:

fstream myFile;
myFile.open("message.txt", fstream::in);
char buffer[150];
while (!myFile.eof())
{
    while (myFile.get(buffer, 150, '\n'))
    {
        cout << buffer;
    }
}

myFile.close();

which gets one line but overall doesn't seem to work. Any ideas?

  • 3
    [Look up `std::istream::getline`](https://en.cppreference.com/w/cpp/io/basic_istream/getline) Also give [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) a read. It'll help solve a bug you haven't found yet. – user4581301 Dec 09 '20 at 18:50
  • 1
    Totally unrelated: don't use the number 150 for the size of the buffer in a read. Some numbnutz could change `char buffer[150];` to `char buffer[128];` for any number of good reasons and miss that `myFile.get(buffer, 150, '\n')` will now overflow. In general [avoid magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad). – user4581301 Dec 09 '20 at 18:53
  • @user4581301 You are totally right about the magic numbers. However, I forgot to mention in my question that I need to read only the first 150 characters from the line or until the line is over. I will edit my question now. – Daniel Halachev Dec 09 '20 at 19:36
  • @user4581301 Thank you. I will surely check them out – Daniel Halachev Dec 09 '20 at 19:36
  • 1
    Remember that one of those 150 characters in the buffer needs to be used by the null terminator. It you want 150 usable characters, the buffer needs to be 151 characters long. – user4581301 Dec 09 '20 at 19:44
  • After reading the sources you gave me, I used `for (buffer; myFile.getline(&buffer[0], MAX_LENGTH, '\n'); ) { cout << buffer << endl; }` It reads all lines except those that are more than 150 characters long. How can I fix it?Also, sorry for prolonging the discussion. I am a beginner in programming. – Daniel Halachev Dec 10 '20 at 12:34
  • The best solution depends on what you want to do with the left-overs on the line. You're probably better off asking a new question with your current code and a sample of the inputs and desired output. – user4581301 Dec 10 '20 at 16:00
  • OK, thank you for all your support. – Daniel Halachev Dec 10 '20 at 16:05

0 Answers0