Whats wrong with this?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string name;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
cout<<"Whats your name?\n";
getline (cin, name);
getline (myfile,name);
cout << name << endl;

}
myfile.close();
}

else cout << "Unable to open file";


system("PAUSE");
return 0;
}





Im trying to make this record what ever you say yoru name is i dont get why it aint working....
I think you have mixed-up input and output files. And you are mixing the file with the console input.

This should help.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
  {
  string name;
  // Create/overwrite my output file
  ofstream myfile ("example.txt",ios::out|ios::trunc);

  if (myfile)  // (only continue if file is opened ok)
    {
    // Give the user instructions
    cout << "Answer the questions.\n"
         << "Press ENTER without answering to quit.\n\n";

    // Ask first question
    cout<<"What's your name?\n";

    // While (there is input --> name)
    //   and (name has data --> user didn't just press ENTER)
    while (getline( cin, name ) && !name.empty())
      {
      myfile << name << endl;  // (write to file)
      cout   << name << endl;  // (write to console)

      // Ask the question again
      cout   <<"What's your name?\n";
      }

    // All done!
    myfile.close();
    }

  else cout << "Unable to open file";

  system("PAUSE");
  return 0;
  }


Hope this helps.
Last edited on
Ty

i edited it a bit and added a quesion its "Where do you come from?" but the quesion keeps going on and on xD it doesnt stop why not??

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
string name;
string location;
// Create/overwrite my output file
ofstream myfile ("example.txt",ios::out|ios::trunc);

if (myfile) // (only continue if file is opened ok)
{
// Give the user instructions
cout << "Please will you answer these few quesions.\n"
<< "If you wish to quit just leave it empty and click ENTER.\n\n";

// Ask first question
cout<<"What's your name?\n";

// While (there is input --> name)
// and (name has data --> user didn't just press ENTER)
while (getline( cin, name ) && !name.empty())
{
myfile << name << endl; // (write to file)
cout << name << endl; // (write to console)

// Ask the question again
cout <<"Where do you come from?\n";
myfile << location << endl; // (write to file)
cout << location << endl; // (write to console)
}

// All done!
myfile.close();
}

else cout << "Unable to open file";

system("PAUSE");
return 0;
}
Topic archived. No new replies allowed.