I'm a c++ newbie here, trying out some stuff and when I try to compile
this:
void create() {
char name;
In the above line you define 'name' as a char. That is, a single
character, 1 byte. Probably not what you want.
cout << "Creating a new timetable /n Please type a name for this
timetable";
cin >> name;
Because, as previously mentioned, name is a char, you read exactly 1
character here.
ofstream editFile;
editFile.open (name, ios:
ut | ios::app);
open expects a POINTER to the first character in an null-terminated
array of characters. If you don't understand pointers and their
relationship to arrays, now is the appropriate time to drop what you are
doing and go read about it.
editFile << name << endl;
}
I get this:
invalid conversion from `char' to `const char*'
Given the above explanation, this message might make sense now. 'name'
is a char, but open wants a pointer to a char.
I kinda understand why i'm getting this since when I change:
editFile.open (name, ios:
ut | ios::app);
To:
editFile.open ("Timetable.txt", ios:
ut | ios::app); , it compiles
When you use a string literal (e.g. "Timetable.txt"), you create a
null-terminated array of characters. And arrays can be implicitly
converted to a pointer to their first element (again, go read about
pointers and arrays if that is new to you), therefore open is getting
what it wants, a pointer to a character.
But how do I get it do do what I want?
A number of ways. First, the not particularly safe, but easier to
understand way:
// I chose the size 80 arbitrarily. This is unsafe.
char name[80] ;
cin >> name ;
This will read from standard input until it sees white space. If there
are more than 79 characters (the null-terminator takes 1 character, read
about C-style strings if this is new to you) available then you have
your classic buffer-overflow problem.
A second, more complicated solution, would be to dynamically allocate an
array, and resize it each time it runs out of space. This is not
trivial to do correctly, so I won't even bother. Let's move on to the
third solution.
Use std::string.
#include <string>
....
std::string name ;
cin >> name ;
....
editFile.open(name.c_str(), ios:
ut | ios::app) ;
std::string does any necessary memory allocating and reallocating for
you. You can get pointer to a null-terminated array of characters using
the c_str method, as demonstrated above.