-
File I/O Question
Hey guys, the following code is part of a program I am working on and as a newbie to c++ I have come across a problem. As you can see when the case is J the int J is increased by 1 but how do I go about doing this if for example instead of J I want to use a word like joke? Is it possible using IF statements?
Thanks in advance for any help.
Code:
ifstream file("c:\file.txt");
if (file.is_open())
{
while (! file.eof() )
{
while (file.get(ch))
{
switch (ch) {
case 'j':
J++;
}
}
}
}
-
A word like "joke" is a string, so to do this with a word instead of a character you must read in a string. Use the string datatype, and read in the word with file >> or getline. Use >> if you want only a single word, use getline if you want the whole line including spaces.
Then you would need to use an if statement instead of a switch, since switch only works with integral types like int or char.
BTW, you would want to put the call to operator>> or getline into the control of your while loop instead of eof(). That is not the best way to loop through the contents of a file because the read itself might fail. The return value of the operator>> call or the getline call automatically tells you if the read succeeded or failed, and so it will catch the end of the file automatically.