xy was not declared in this scope: compiler error!
Hey everybody,
I finished lesson 10 today, fileio, and thought "Hey, let's combine all I have learned before.
So I programmed a simple menu with switchcase, and thought I would give the user the choice between writing something into a file, read a file and print the content out, append something to a file or exit.
But when I wanted to test my first function (i.e. write something to a file) I get the following errors and can't quite figure it out :-( I bet it is quite simple!!
Any help is highly apreciated :-)
Code:
~ thommy$ g++ switchfileio.cpp -o littletest
switchfileio.h: In function ‘void write_file()’:
switchfileio.h:15: error: ‘cout’ was not declared in this scope
switchfileio.h:16: error: ‘cin’ was not declared in this scope
switchfileio.h:21: error: ‘ofstream’ was not declared in this scope
switchfileio.h:21: error: expected `;' before ‘a_file’
switchfileio.h:22: error: ‘a_file’ was not declared in this scope
switchfileio.h: In function ‘void read_file()’:
switchfileio.h:28: error: ‘cout’ was not declared in this scope
switchfileio.h: In function ‘void appendto_file()’:
switchfileio.h:32: error: ‘cout’ was not declared in this scope
:~ thommy$
This is what I got so far:
File: switchfileio.cpp
Code:
#include <iostream>
#include <fstream>
#include "switchfileio.h"
using namespace std;
int main(){
int input; // need this one for the switch-case-menu
do { // this is the menu, it works, have tried this with another lesson!
cout<<"1. Write something to a file\n";
cout<<"2. Read a file and print its content\n";
cout<<"3. Append a string to an existing file\n";
cout<<"4.Exit\n";
cin>>input;
switch (input) {
case 1:
write_file();
break;
case 2:
read_file();
break;
case 3:
appendto_file();
break;
case 4:
cout << "Thanks for playing with me\n";
break;
default:
cout<<"Error\n";
break;
}
} while (input == 1 || input == 2 || input == 3 || input == 4); // this is to redraw the menu when one operation is done
cin.get();
}
File: switchfileio.h
Code:
void write_file(){ // my function that is called when the user wants to write a file
char string[256]; // this is the string the user can enter
char filename[15]; // this string is used to determine the filename of the file
cout << "Please enter your text!\n";
cin >> string;
cout << "You entered: " << string <<"\n"; // show the user what he has written
cout << "Please enter a filename: "; // ask for the filename
cin >> filename;
ofstream a_file (filename); // creates an instance of ofstream and opens a file with the content of filename
a_file<<string; // write the content of "string" into the file
a_file.close(); // close the file
cout << "file " << filename <<" is written!\n"; // give success message to the user
}
void read_file(){
cout << "you just loaded\n";
}
void appendto_file(){
cout << "sorry, MP is not ready yet\n";
}