So, I'm going to be up front, this may get my question taken down, but I don't have a lot to go off of so this may be an incomplete question, but I'm completely stuck. I am writing a program in C, to be able to count the occurrence of a character that is provided by the user. I am currently, trying to save the characters with getchar() within a while loop, as I try to display the results it gives me the whole input inside the loop, but when it exits the loop it saves the last char character (i understand why it is doing this, just not how to fix it). NOTE: This code contains extra parts not necessary to answer this question, those are for later on in my code. :) Here's my current code (3/12/18), I'm sorry I can't be more thorough:
#include<stdio.h>
#include<stdbool.h>
#include<string.h>
#define N 26
int main(void) {
char ch, index;
int count[N] = {0}, tolower(int ch);
printf("Enter a sentence (end by '.'): \n");
while(ch != '.') {
ch = getchar();
putchar(ch); \\print testing to see where the characters are "leaving"
}
printf("%c", ch); \\print testing to see if the characters go past the loop
}
You need to do the loop events in this order:
'.'
or EOF
Also, you need to use int
to store the return value of getchar()
because otherwise you have no way of checking for EOF
(which is not a character).
If you literally translate those steps to code you would get:
int ch;
for (;;)
{
ch = getchar();
if ( ch == '.' || ch == EOF )
break;
putchar(ch);
}
although it is a common idiom to combine the first two statements into the loop condition:
int ch;
while ( (ch = getchar()) != '.' && ch != EOF )
putchar(ch);