kate2007

I was working on an exercise: Create a program that opens a file and counts the whitespace-separated words in that file. The follwing is the correct answer I copied from solution mannual, but the output is
Number of words = 0
which is oviously wrong. I was wondering what the problem could be.
I did put the following code in a different project from the one that contains "helloworld.cpp".

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream f("helloworld.cpp");
int nwords=0;
string word;

while (f >> word)
++nwords;

cout << "Number of words = " << nwords << endl;
}


Re: Visual C++ Language Create a program that opens a file and counts the whitespace-separated words in that file.

Tomay

For me, the code works perfectly fine. Make sure, that you have helloword file in the same directory than the running program.
Maybe add this line to se if you have file available:
if( !f.is_open))
cout << "There isn't no such file!\n";





Re: Visual C++ Language Create a program that opens a file and counts the whitespace-separated words in that file.

kate2007

Hi Tomay, Thanks for your reply!

I copied the line into my file, but the following error info came up:

Error 1 error C2276: '!' : illegal operation on bound member function expression
Error 2 error C2059: syntax error : ')'

I deleted "!", and ")", and then I have

Error 1 error C3867: 'std::basic_ifstream<_Elem,_Traits>::is_open': function call missing argument list; use '&std::basic_ifstream<_Elem,_Traits>::is_open' to create a pointer to member

I don't know how to fix it.

Also, the helloworld file is in the same directory of the running one, but didn't work. I tried another file in the same directory, it worked. It seems strange to me. I didn't know what the problem it could be.








Re: Visual C++ Language Create a program that opens a file and counts the whitespace-separated words in that file.

Bite Qiu - MSFT

Above code missed a '(':

Code Snippet

if( !f.is_open())
cout << "There isn't no such file!\n";

Please also make sure that helloworld.cpp does not opened by another program.






Re: Visual C++ Language Create a program that opens a file and counts the whitespace-separated words in that file.

twiztid2k6

hay on "helloworld.cpp" edit it to "hello.cpp" did the trick for me