Hello everyone im currently using Xcode to do my c++ class online, i have a question here that im suppose to answer.
Question is : Write a program that opens a file and counts the whitespace-separated words in that file.?
my answer is :
#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();
}
now im not sure if im suppose to get a msg saying :
The file "Question 1.cpp" has 0 words.
im wondering is the question that im being asked, asking me to input a string of words and then the compiler when it builds and runs the program counts the word spaces.?
See my friend helped me out with it and he sent me the answer to the question now im just trying to understand it my friends away overseas now so im out of luck asking him. Is the Question 1.cpp suppose to be a file that will be opened in program when run containing a array or string?
Can i go about it a different way as in saying cout<<write a string etc.. and then user inputs a string where it is then counted for the white spaces?
That the program opens a file just means that it makes it ready to be read from. It does not mean that you will see the file in a text editor or anything like that. It is this line ifstream file(filename); that opens the file. You probably get "0 words" because there is no file named "Question 1.cpp".
The description says you should read from a file so you are not supposed to read the words from the the user. It doesn't say which file to read from so I guess you can use a different filename or let the user decide if you want.