Reading files with ifstream

I am making a simple program which gives you the option of either writing some text and saving it to SAVEDATA.txt, or loading text from SAVEDATA.txt. However I'm getting some errors.

Here is my code: (I am using VC++ 2008 Express Edition)

[code=cpp]#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
int choice = 0;
string saveText;
string loadText;
cout << "1: Write Text.\n2: Load Text.\n\n";
cin >> choice;

//OPEN FSTREAM

ofstream myfile;

switch( choice )
{

//SAVE TEXT

case 1:
myfile.open("SAVEDATA.txt");
cin >> saveText;
myfile << saveText;
myfile.close();
break;

//LOAD TEXT

case 2:
ifstream myfile("SAVEDATA.txt");
myfile.open("SAVEDATA.txt");
getline( myfile, loadText );
cout << loadText;
myfile.close();
break;

//INVALID

default:
cout << "Invalid choice.";
}

system("PAUSE");
return 0;
}[/code]

And here is the build log: (Errors bolded.)

1
2
3
4
5
6
7
8
9
10
1
1>Compiling...
1>FstreamConsole.cpp
1>c:\documents and settings\brad\my documents\visual studio 2008\projects\fstreamconsole\fstreamconsole\fstreamconsole.cpp(42) :
 error C2361: initialization of 'myfile' is skipped by 'default' label
1>        c:\documents and settings\brad\my documents\visual studio 2008\projects\fstreamconsole\fstreamconsole\fstreamconsole.cpp(34) :
 see declaration of 'myfile'
1>Build log was saved at "file://c:\Documents and Settings\Brad\My Documents\Visual Studio 2008\Projects\FstreamConsole\FstreamConsole\Debug\
BuildLog.htm"
1>FstreamConsole - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========



Last edited on
You can't just change the type of a variable in the middle of the code. (Line 34) You have to give it a different name.
Topic archived. No new replies allowed.