Reputation: 13
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
Upvotes: 0
Views: 4032
Reputation: 56509
You are comparing the address of i
th character with the address of const literal "\n"
which is useless. To compare a character with character \n
, you should use single quotes: '\n'
and remove &
operator also.
if (dataArray[i]=='\n')
Forget Turbo C++ and use new and modern compilers
After update
You should try to use STL and managed containers rather and your pointer stuff and new/delete
. Moreover, testing by .eof()
is not a good practice, use the object itself. And to get a line, you can use std::getline
function. Rewriting your code in a standard new compiler:
ifstream playerData("players.txt");
while(playerData) {
string dataArray;
getline(playerData, dataArray);
cout << dataArray << '\n';
}
Upvotes: 1
Reputation: 141628
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:
i<=size
to i < size
new
for no reason; use an array instead>>
operation succeeded.while(!playerData.eof())
is a blunder; instead you should break when >>
failsAlso, 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:
Upvotes: 4