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