>You can't compare strings the way you do.
Sure you can. The string class overloads the relational operators. Though needs to be included.
>the file never opens correctly
Try this:
#include <iostream>
#include <fstream>
#include <cassert>
#include <string>
using namespace std;
int main()
{
int numberOfWords;
string fileName;
string wordString;
cout << "File to process (type quit to exit): ";
cin >> fileName;
while(fileName != "quit")
{
ifstream infile(fileName.c_str());
assert(infile);
infile >> wordString;
for(numberOfWords = 0; infile; numberOfWords++)
{
infile >> wordString;
}
cout << fileName << " has " << numberOfWords
<< " words." << endl << endl;
cout << "File to process (type quit to exit): ";
cin >> fileName;
}
}
>assert(infile);
No. assert is designed as a debugging tool, not as a run-time error handling mechanism. Failure to open a file is not considered a programming error, it's an input error in this case. So you should be using a conditional statement:
if (!in) {
cerr<<"Failure to open file"<<endl;
// Terminate here or handle the error
}
I know it's subtle, but a program error and a programming error are two completely different things and need to be dealt with in different ways.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>He wanted us to use that instead of an if statement.
Tell him I said he's a bad teacher.
>Any more suggestions?
...Well, if you bothered to read the code I gave you, you'll find that I changed more than just adding "#include ". :rolleyes: Try running the code.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
First, are you using the exact code that I posted? Second, what compiler are you using?
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Is that all?
Well, I could have rewritten it entirely:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
bool getfile(string& file)
{
cout<<"Enter a file to open: ";
return cin>> file ? file != "quit" : false; // w00t!
}
int main()
{
string file;
while (getfile(file)) {
ifstream in(file.c_str());
if (!in) {
cerr<<"Error opening file"<<endl;
return EXIT_FAILURE;
}
string word;
int n = 0;
while (in>> word)
++n;
cout<< file <<" has "<< n <<" words"<<endl;
}
return EXIT_SUCCESS;
}
But why do more than you have to? ;)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>why are my code tags not working on the board???
It looks as if you aren't using a closing tag. Do this (without the spaces):
[ code ]
// Code goes here
[ /code ]
>I din't mean to belittle your work by saying "is that all?"
No worries, I didn't see it as belittling. Often it's a simple and subtle change that's the difference between broken code and working code.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401