Need Help Please!!:(

Hello Everyone,

I need to complete my assignment for my lab im stuck and cant figure out what to do to solve my problem.


Write a program that opens a file and counts the whitespace-separated words in that file.?

My code that i wrote for this example is as follows...






#include <iostream>

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

int main()
{
string filename = "Question 1.cpp"; // File name goes in here
ifstream file(filename);
int wordcount = 0;
string word;

while (file >> word)
++wordcount;

cout << "The file \"" << filename << "\" has " << wordcount << " words." << endl;
cin.get();
}

i know this is wrong but i cant seem to understand the concept of counting the whitespaces...
Pleaseee help me out..

Last edited on
I don't see anything wrong.
Last edited on
How much does it go wrong?
Im not sure if i quite understand the question being asked of me... I thought i would have to input a sentence or (string) into the program and it would tell me the amount of white spaces..


Can you guys try and see if this actually will run? Im running this on Xcode so im not sure since im not too familiar with Mac and the program Xcode..
Write a program that opens a file and counts the whitespace-separated words in that file.
In other words: Count the number of words in the file. The words are separated by whitespace characters.

That is exactly what this loop is doing.
1
2
while (file >> word)
	++wordcount;
Line 11: error: no matching function for call to 'std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)'
compilation terminated due to -Wfatal-errors.

what exactly does that mean
It means that ifstream doesn't have a constructor that takes a std::string as argument. This constructor has recently been added to C++ but if your compiler does not support it you will have to pass a const char* (aka C string) instead. You can get a const char* from std::string by using the c_str() member function.

ifstream file(filename.c_str());
Topic archived. No new replies allowed.