Discussion Locked

Question about C++

0 helpful
4 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
ok I have to write a program that goes into a text file and counts how many spaces between the words there are and outputs that number. how would I go about doing this???

4 replies

by mmmova

This solution is in Borland Tubo C++ 3
All you have to do is to first of all open a file pointer that points to your file. Then you have too use an infinite loop a do while or while loop and fetch each character using fgetc()
function and check the character against space, if it is found increment a variable and at the end of loop, print the count.
a sample would be,

#include
void main()
{char current;
int spaceCount=0;
FILE *fp; fp=fopen(c://yourfilepath//yourfilename.txt","r+");

current = fgetc(fp);

while(current!=EOF)
{
current=fgetc(fp);
if(current==' ')++spaceCount;
}
fclose(fp);
printf("The number of spaces: %d",spaceCount);
getch();
}

by joltinjim

This solution has a small problem, it does not check to see if the first character is a space.
I would suggest substituting the following code for the loop:

current = fgetc(fp);
while()
{
if(current==' ')++spaceCount;
else if(current==EOF)break;
current=fgetc(fp);
}

by shajithchandran

The problem here is that the type of the variable "current" is char which cannot hold EOF. It is quiet possible that the loop will terminate before reaching the end of file. If the file contains all the ASCII characters (including 0xff), then the program will end the moment ur program read this character.

by mekijemal

I am taking a programing course in c++. How can I get a material that leads me to proficiency in C++. Thank you

This discussion is closed to new replies.