Friday, October 26, 2018

c++ - Why does ofstream give me an echo ie. writes input twice

When I run the following code, and I write for example "Peter" then the result is that I get "PeterPeter" in the file.



Why?



#include "stdafx.h"
#include "iostream"
#include "iomanip"
#include "cstdlib"

#include "fstream"
#include "string"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
ofstream File2;
File2.open("File2.dat",ios::out);


string name;
cout<<"Name?"< while(!cin.eof())
{
cin>>name;
File2< }
return 0;
}



When I change the while loop to



while(cin>>name)
{
File2<}


it works. But I don't understand why the first approach does not.




I can't answer my own question (as I don't have enough reputation). Hence I write my Answer here:



Ahhhh!!! Ok Thanks. Now I got it ^^



I have been testing with



    while(!cin.eof())
{
cin>>name;

File2< cout<}


What happens is that when I tip crtl+z he is still in the while loop. The variable name stays unchanged and is added to "File2" in the next line of code.



The following is working:



while(!cin.eof())

{
cin>>name;
if(!cin.eof()){File2< cout<}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...