0

Hey I know I can just use a string to read from a text file. However I need to use a char array. Like If I was using a string I would do this

while (!input.eof()){
    input >> s;
}

I am unsure how I would go about this if I don't know the length of the string. I know I can use getLine, but I'll prefer to use input.

I'm thinking that maybe I can use a loop to check until it reaches "\0"?

Anyway I have a feeling this question has been asked before, but if it has I can't find it. So sorry if that is the case.

Andy
  • 1
  • Regarding your posted code: I wouldn't do that. Read this for why: [Why is `iostream::eof` inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – WhozCraig Nov 11 '16 at 04:56
  • 2
    Is there a reason why you don't want to use `getline`? – celtschk Nov 11 '16 at 07:04

1 Answers1

0

You can consider istream::getline. Note that it can be use for C++ string and it must have a length limit for C string.

I think you should avoid check eof directly in while condition. It only returns true it reach end-of-file. So if you have multiple line, you read it, then do some calculate, the consequence can be unexpected when it reach the end-of-file right at reading step. So the check of EOF should be placed right after reading from stream like my example.

int main()
{
    ifstream input("filename.txt");
    const int MAX = 10000;
    char characters[MAX];
    while (true) {
        input.getline(characters, MAX - 1, '\n');
        if (input.eof())
            break;
    }
}
khôi nguyễn
  • 626
  • 6
  • 15