Question on use of classes
Hello all. I have a very simple exercise to do. On notepad, I create a file called filelab.txt. The only thing in this file is the sentence "C++ is fun" (without the quotes, just the sentence). So what I'm supposed to do is: Read in each letter(from the file) separately, and then display (on the screen) as it is read in from the file, stopping at "n".
2 conditions:
1) Do not use a loop to read.
2) I must use classes.
I have finished this problem, and it works fine, but without classes. I'm not really sure how to do it with classes.
Here's the code:
Code:
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
int main ()
{
ifstream infile("A:filelab.txt", ios::nocreate); //this opens up the file
char a, b, c, d, e, f, g, h;
infile >> a;
cout << a << endl;
infile >> b;
cout << b << endl;
infile >> c;
cout << c << endl;
infile >> d;
cout << d << endl;
infile >> e;
cout << e << endl;
infile >> f;
cout << f << endl;
infile >> g;
cout << g << endl;
infile >> h;
cout << h<< endl;
infile.close();
return 0;
}
now my questions are:
1) Where would the "ifstream infile("A:filelab.txt", ios::nocreate); //this opens up the file " command go, in the source file? I don't think it goes in the main or the header file, but not sure.
2)What is the class of? All the program does is read a sentence from a file, and output to screen. So what is the class about in this case, the sentence? I'm having a hard time with this, what's the class, the object, in the problem?
Thanks for any feedback!
Well, now it's too late, but...
With a character array, you don't have to add new variables if the text-string gets longer. And, character arrays are a standard (normal) way of handling strings.
However, upon further thought... in your program, you only need one variable! Since you are displaying the character immediately, and you don't need to save it... You can overwrite the variable with a new value each time you read a new character.
Code:
infile >> a;
cout << a << endl;
infile >> a;
cout << a << endl;
infile >> a;
cout << a << endl;