Search code examples
c++turbo-c++borland-c++

Read from text file in Turbo C++ 3.0


First post. Please let me know if I missed anything, or if you require any more information.

Okay, so what I'm trying to do here is read data from a text file in Turbo C++ 3.0, and then output this text.

Here is my code (updated):

ifstream playerData("players.txt");
const int size = 100;
char* dataArray = new char[size];

while(!playerData.eof()){
    for(int i=0; i<size; i++){
        playerData>>dataArray[i];
        if(dataArray[i]=='\n'){
            cout<<"\n";
        }
        cout<<dataArray[i];
    }
}

If I have the following text in the players.txt file:

ABC - 7 minutes
DEF - 4 minutes

Then this is what is outputted:

ABC-7minutesDEF-4minutes

Solution

  • I don't know what &(dataArray[i])=="\n" is supposed to be. It looks like you just guessed things until compiler errors went away. That's not a good way to code any language, let alone C++.

    What you've written tests whether the element dataArray[i] lives at the same memory address as the literal array "\n". They certainly don't, so this test will always fail.

    If you meant to compare against a char, write if (dataArray[i] == '\n'). However, that would still be a mistake because dataArray[i] has not been assigned a value yet. You should move the line to after you read into dataArray[i].

    Other problems:

    • You overflow the buffer, change i<=size to i < size
    • You use new for no reason; use an array instead
    • You don't check whether your >> operation succeeded.
    • while(!playerData.eof()) is a blunder; instead you should break when >> fails

    Also, Turbo C++ 3.0 came out before the first C++ standard, so it is not a good idea to use it for C++. In summary:

    • learn from a book, not trial-and-error
    • Get a modern compiler (there are good free ones)