I have tried for hours to edit this code to work the way I want it to. I am meant to code a program to track the frequency of how often an underscore '_' and an exclamation point '!' appear in a sentence input by a user: _Hi_there!!!
Specifications that must be used and/or not deleted -This function prototype must remain unmodified: -The getchar() method must be used to hold the value of the sentence input by the user.
Now I have this code after hours of struggling to get a proper output:
#include <stdio.h>
int num_count;
int num_exclamation_count;
char ch;
char s[1000];
void count(int* num_, int* num_exclamation)
{
int i;
for(i = 0; s[i] != '\0'; i++)
{
if((s[i] == getchar()) && (s[i] == '_'))
{
++num_count;
*num_ = num_count;
}
else if((s[i] == getchar()) && (s[i] == '!'))
{
++num_exclamation_count;
*num_exclamation = num_exclamation_count;
}
else
{
continue;
}
}
}
int main (void)
{
int num_user, num_exclamation_user;
printf("Enter a sentence: ");
do
{
ch = getchar();
}while(ch != '\n');
count(&num_user, &num_exclamation_user);
printf("There are %d underscores and %d exclamation points in the
sentence.\n", num_user, num_exclamation_user);
return 0;
}
The output I get is as follows:
There are 0 underscores and 0 exclamation points in the sentence.
I tried every variation of while or if or do-while statements I could conjure in my mind or find available online and I get nowhere but further away. If someone could thoroughly explain how I arrange which conditional statement/loop with the getchar() method and necessary variables, that would be awesome. Open to criticism as well if I blatantly screwed something up or passed over an obvious issue, do not be scared to hurt my feelings. I only want to learn and will be my only mindset as I am assisted with this problem.
Thank you.
OP's code has these errors:
Not initializing num_user, num_exclamation_user
in main()
. Set them to 0
Unneeded code of do { ch = getchar(); while (ch != '\n');
in main()
. Delete
Looking for a null character from input with for(i = 0; s[i] != '\0'; i++)
prevented loop iteration as s[0]
is initialized to 01. User input is lines, not a string. Look for a '\n
'. Also assign s[i] = getchar()
, not compare s[i] == getchar()
@wildplasser
//for (i = 0; s[i] != '\0'; i++) {
for (i = 0; i < 1000 && (s[i] = getchar()) != '\n'; i++) {
Code calls getchar()
more than once per loop.
// if ((s[i] == getchar()) && (s[i] == '_')) {
if (s[i] == '_') {
...
// } else if ((s[i] == getchar()) && (s[i] == '!')) {
} else if (s[i] == '!') {
Although there are other learner issues (e.g. better to use int ch
for input than a char s[i]
), fixing the above will solve OP's problem.
1 Global integer types like the array s[1000]
elements are initialized to 0.
Short count()
below. Think it out before mousing over.
void count(int* num_, int* num_exclamation) {
int ch; while ((ch = getchar()) != '\n' && ch != EOF) {
if (ch == '') {
(*num)++;
} else if (ch == '!') {
(*num_)++;
}
}
}