Im not sure how to write this segment of code. My goal here is to ask user for a file name, then read in the file one character at a time into a stack class reference object "DoubleStack dblStack;". This is what i have so far...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main (void)
{
string fname;
cout << "Enter name of file to open: \n";
cin >> fname;
ifstream in;
in.open(fname);
assert (in.is_open());
while (!in.eof())
{
for (int i = 0; i <= STACK_CAPACITY; i++)
{
myCharArray[i];
dblStack = myCharArray[i];
}
}
}
Is this right?
Suggestions, tips, constructive criticism?
Line 14 might be something like dblStack.push( myCharArray[i] ); //push the char on to the stack
It depends on your class DoubleStack, and its methods.
I'm terribly sorry for not explaining this better. The two stacks are implemented with a dynamic array. The array is declared and initialized in two header files not mentioned here. Sorry for the confusion. Also, I realize now that i could have just used push to do what I needed and feel very stupid after having noticed lol
In addition to what others have said you should not loop on in.eof(). It is better to loop on the stream state after the get() has been called. That way you know that your char is valid. Also assert() is not suited to checking user input.
#include <fstream>
#include <iostream>
usingnamespace std;
//int main(void) // void not needed
int main()
{
string fname;
cout << "Enter name of file to open: \n";
cin >> fname;
ifstream in;
in.open(fname.c_str()); // can't pass std::string to open()
// assert (in.is_open()); // Not a good use of assert()
// Better to use if()
if(!in.is_open())
{
std::cout << "Could not open file: " << fname << '\n';
return 1; // return 1 to indicate error
}
// while (!in.eof()) // Almost never the right thing
// check the *result* of the get() to determine if it worked
char c;
while(in.get(c)) dblStack.push(c);
}
So I've taken what i've learned from all that and revised this section in my driver. How does it look now?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int main()
{
string fname;
cout << "Enter name of file to open: \n";
cin >> fname;
ifstream in;
in.open(fname.c_str());
if (!in.is_open())
{
std::cout<< "Could not open file: " << fname << '\n';
return 1;
}
else
{
char c;
if (in.get(c))
{
myCharArray[c];
//to be continued...
at this point in the code, i need to determine if the character is a capital letter or a lowercase letter and place them in either stack one (lowercase letters) or stack two (capital letters). I have no clue how to do this...