Hello everybody, I'm working on a program that reads from a file a sequence of numbers and push them into a stack. I give the file name that containn the numbers manually into a function of the stack. What if I want to let the program read the file name from the keyboard in the main function? Does exist a method to do it? Thanks for your time, I leave the code of my program below.
There's a really easy way to handle this sort of problem. When designing your class, don't write methods that "do the work." Write methods that "make doing the work easy." If you think like this, you'll write code that is much more flexible.
In this case, you have a method called autopush() that pushes items from the file "nums.txt" onto the stack. That's useful for one thing and one thing only. It would be much more useful and flexible if autopush() pushed items from an existing istream:
1 2 3 4 5 6
void stack::autopush(istream &is) {
int num;
while (is >> num) {
push(num);
}
}
This is slightly different from what you have because it reads all items from the file, but that's probably what you want.
Now in main you do
1 2
ifstream strm("nums.txt");
st1.autopush(strm);
Notice that this doesn't even involve more code. It just moves the stream to a different place. But look what you can do now:
1 2 3 4 5 6
// push the numbers from cin:
stk.autopush(cin);
// push a bunch of nums
istreamstream ss("2 4 6 8 10 12");
stk.autopush(ss);
BTW, you should add error checking code to push() to deal with the case where the stack is full. Either create more space or don't push the item.
Hi dhayden! Thanks for your answer. What you wrote was really useful for me! Thanks! But I wanted to know if its possible to write from keyboard the name of the file that has to be red.
For example:
The program asks the name of the file, then try to open it, is it possible?