Hello everybody!
I'm trying to count the number of occurrences of each word in a text file. Problem situation requires to realize menu using "switch" statement (If file exist or not). There are following errors in my program ("case b" and "default" is not working):
[C++ Error] 03_int.cpp(61): E2126 Case bypasses initialization of a local variable
[C++ Error] 03_int.cpp(72): E2238 Multiple declaration for 'w'
[C++ Error] 03_int.cpp(50): E2344 Earlier declaration of 'w'
[C++ Error] 03_int.cpp(83): E2126 Case bypasses initialization of a local variable
#include <fstream.h>
#include <iostream.h>
#include <map.h>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <conio.h>
typedef std::map<std::string, int> StrIntMap;
void countWords(std::istream& in, StrIntMap& words)
{
std::string s;
while (in >> s)
{
++words[s];
}
}
using namespace std;
int main(void)
{
char str[80];
FILE *fp;
char input;
cout << "a. File exist and empty\n"
<< "b. File is not exist";
cin >> input;
cin.ignore(1000, '\n');
switch (input) {
case 'a':
fp = fopen("TEST.dat", "a");
do {
cout << "Enter a string (CR to quit):\n";
gets(str);
strcat(str, "\n"); /* add a newline */
fputs(str, fp);
} while(*str!='\n');
fclose(fp);
ifstream in("TEST.dat");
StrIntMap w;
countWords(in, w);
for (StrIntMap::iterator p = w.begin( ); p != w.end( ); ++p)
{
std::cout << setw(20) << left << p->first << " occurred "
<< setw(5) << right << p->second << " times.\n";
}
break;
case 'b':
fp = fopen("TEST.dat", "w");
do {
cout << "Enter a string (CR to quit):\n";
gets(str);
strcat(str, "\n"); /* add a newline */
fputs(str, fp);
} while(*str!='\n');
fclose(fp);
ifstream inFile("TEST.dat");
StrIntMap w;
countWords(inFile, w);
for (StrIntMap::iterator p = w.begin( ); p != w.end( ); ++p)
{
std::cout << setw(20) << left << p->first << " occurred "
<< setw(5) << right << p->second << " times.\n";
}
break;
default:
cout << "Enter a or b";
}
return 0;
}
What should I search for in my code in order to find the problem? Is it possible to realize counting without "ifstream"?
Thanks in advance.