Hey,
I have been attempting to learn some C++ (very novice stuff) but I was trying to write a couple of simple programs to try and learn the basics.
I've started on a word counter, with a word finder attached. You search for a word, and it tells you how many times it is included. This was just to try and learn some of the basic syntax, I'm sure it could be implemented in a better way
Here is my attempt at code:
Now, I have a couple of questions about this. Firstly, it won't run as it says the function findWord is not properly declared, but I can't quite understand why. Secondly, I have done it this way, using only iostream, so was wondering what the advantages, if there are any, were of using stdio and scanf/printf rather than this way?Code:#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myfile ("eg.txt",ios::in); if (myfile.is_open()) { string x; string readStr; string searchWord; int noWords = 0; while (myfile >> x) { readStr = readStr + " " + x; noWords++; } myfile.close(); cout << "The number of words in this file is: "; cout << noWords; cout << "\n\nSearch for word?\n"; cin >> searchWord; findWord(searchWord); } else cout << "Cannot open file"; return 0; } int findWord(string searchStr) { ifstream myfile ("eg.txt",ios::in); if (myfile.is_open()) { string x; string readStr; int noFound = 0; while (myfile >> x) { if (x==searchStr) { noFound++; } } myfile.close(); return noFound; } else { cout << "Cannot open file"; return 0; } }
Those questions might make no sense, I really am just learning the basics atm, so any help would be greatly received.
Thanks a lot!
First, findWord isn't seen by main because you haven't declared it. You can either put a prototype above it (int findWord(string); ) or you can move the whole function above main.
Secondly, iostream is C++ and stdio.h is C. Seeing as you are using std::string you don't want to start mixing it with C functions.
Last edited by Naeth; 10-18-2009 at 02:57 AM. Reason: Stupid smily
Yeah. You might want to read this too: bit.ly/1mEmjr
(Cant post URL's yet. Had to use bit.ly)
Thanks very muchAppreciate that!
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks