Hi all.
i just make some code to reverse a string.but problem is it's making garbage.
like it read "hello world" from input.txt ,no problem but in output.txt u will find just dddd......what to do
plz help *********
Why do you have two read() loops? The first one seems to count the characters in
the stream, and the second one seems to want to read the characters into the array.
But the stream is already at EOF, so the second one does nothing.
Having said that, the way you are reading is wrong.
1 2 3 4 5
while( Read ) {
Read.get( t );
if( Read )
i++;
}
You have to check to ensure that get() actually got something. The problem is that
EOF is not true until you attempt to read PAST EOF.
int main()
{
ifstream Read("input.txt");
char t;
int i=0;
while (!Read.eof()){
Read.get(t);
i++;
cout <<i<<" "<<t<<endl; //Please observe Reading prosess.why last char repeat
}
cout << "number of charcter is:"<<i<<endl;
// your code didn't compile since arrays can't be done with variable.
std::vector<char> a(i);
for (int e=0;e<=i;e++){
Read.get(t);
a[e]=t;
}
ofstream Write("output.txt");
for (int e=i;e>=0;e--){
Write<<a[e];
}
Write.close();
cin.get();
return 0;
}
Your code wouldn't compile for me so I posted the change that I made. There are many ways to rewrite your program. now take a look at this. I searched google for "c++ eof last read twice". Remember, google is your friend. http://www.daniweb.com/forums/thread11837.html#
The problem with the last line being read twice is that EOF isn't set until you try to read past the end of the file. Therefore, your loop is fundamentally flawed. After you read the last character, EOF hasn't been set so it goes in one more time and tries to read the file. However, note that the last character is NOT being read twice. Stale data is being reprinted because the local variable wasn't updated.
If you insist on using a character array you'll have to dynamically allocate the memory for the array and follow the pattern in this example. Get rid of the loop and read the entire file at once. http://cplusplus.com/reference/iostream/istream/read/