Question

I am running this code using C to count the words in char array, but somehow...

I am running this code using C to count the words in char array, but somehow it keeps counting the total characters + 1.

Any solution to fix this problem?

#include <stdio.h>

int main()
{
   char input[1001];
   int count =0;

   fgets(input, 1001, stdin);
   char *array = input;
   while(*array != '\0')   
   {
       if(*array == ' '){
           array++;
       }
       else{
       count++;
       array++;
       }
      
   }
   printf("this character's length is %d.", count);
   printf("this characterarray : %s", input);
  

   return 0;
}

Homework Answers

Answer #1

Thank you for the question.

Here is the catch !!

When ever you are using fgets() function, it also stores the newline character into the string.

So if the string entered is "abc" and then you hit the Enter key , the array will store the string as 'a','b','c','\n','\0' . So you can see total characters is 4 and not 3

So you need to decrement the count by 1 after the while loop ends. I have updated the code and it works fine now.

thank you

======================================================================================

#include <stdio.h>

int main()
{
char input[1001];
int count =0;

fgets(input, 1001, stdin);
char *array = input;
while(*array != '\0')   
{

// dont count white space line feed or new line characters
if(*array == ' ' || *array=='\n' || *array=='\r'){
array++;
}
else{
count++;
array++;
}
  
}

printf("this character's length is %d.", count);
printf("this characterarray : %s", input);
  

return 0;
}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Debug code to get it to only count non alpha numeric values. Right now it always...
Debug code to get it to only count non alpha numeric values. Right now it always outputs zero. Why? please explain /*Problem 1*/ #include <stdio.h> #include <string.h> #include <stdlib.h> int loop_count; char scanned_line[100]; int non_alpha_num_checker = 0; int total; int main() { printf("Enter a line: "); fgets(scanned_line,sizeof scanned_line, stdin); for(loop_count = 0; loop_count != '\0'; loop_count++){ if(scanned_line[loop_count] >= 'A' && scanned_line[loop_count]<='Z') { continue; }    else if(scanned_line[loop_count] >= 'a' && scanned_line[loop_count]<='z') { continue; } else if(scanned_line[loop_count] >= '0' && scanned_line[loop_count]<='9')...
I am trying to write a program in C language but keep running into errors. Any...
I am trying to write a program in C language but keep running into errors. Any help would be awesome. here is my code I have so far. #include <stdio.h> #include <conio.h> #include <string.h> int main(){    int lenght, i = 0, state = 0;    char line[100];    printf("enter the string for checking of comment line: \n");    gets(line);    while(i < strline(line)){        switch(state){            case 0: if (line[i] == '/'){               ...
Question 3. In the following code, answer these questions: Analyze the code and how it works?...
Question 3. In the following code, answer these questions: Analyze the code and how it works? How can we know if this code has been overwritten? Justify how? #include <stdlib.h> #include <unistd.h> #include <stdio.h> int main(int argc, char **argv) { int changed = 0; char buff[8]; while (changed == 0){ gets(buff); if (changed !=0){ break;} else{     printf("Enter again: ");     continue; } }      printf("the 'changed' variable is modified\n %d", changed); }
I am trying to write a program that reads a string (in my case a domain...
I am trying to write a program that reads a string (in my case a domain name). What I am struggling with is how to traverse through the array and see if there are any invalid characters in the string such as a semi colon or a space. Here is what I have as of now. #include <stdio.h> int main() {    char min[1];    char max[253];    char domain[253]; printf("Enter a domain: "); scanf("%s", domain);    return 0; }
Please answer the following C question: There is a documented prototype for a function called get_a_line...
Please answer the following C question: There is a documented prototype for a function called get_a_line in the code below. Write a definition for get_a_line—the only function called from that definition should be fgetc. #include <stdio.h> #include <string.h> #define BUFFER_ARRAY_SIZE 10 int get_a_line(char *s, int size, FILE *stream); // Does what fgets does, using repeated calls to fgetc, but // provides a more useful return value than fgets does. // // REQUIRES // size > 1. // s points to...
q7.3 Fix the errors in the code (in C) //This program uses a function called CharacterScan...
q7.3 Fix the errors in the code (in C) //This program uses a function called CharacterScan to read a char from the user //The function must take an int pointer as a parameter //The program should print the char and ascii code for each character the user enters //The program should only exit whe nthe user enters escape #include <stdio.h> char CharacterScan(int*); int main(void){ while(1){ int aCode; int* iPtr; char* c = CharacterScan(iPtr); if(aCode) break; else printf("%c is ASCII code...
I'm trying to find a code to check the occurrences of the word or string I...
I'm trying to find a code to check the occurrences of the word or string I wrote my own code but it's not working can you please help and fix my code #include <stdio.h> #include <string.h> #define MAX_SIZE 100 // Maximum string size int main() { char str[MAX_SIZE]; char tosearch[MAX_SIZE]; printf("Enter any string: "); gets(str); printf("Enter word to search occurrences: "); gets(tosearch); int cursor = 0; int i = 0; int stringLen = 0; int searchLen = 0; int count1;...
would someone kindly convert the following C code to java? thanks so much # include <stdio.h>...
would someone kindly convert the following C code to java? thanks so much # include <stdio.h> int main(void) { int changeOwed; int check; char invisibleChar; int count = 0; int numQ=0, numD=0, numN=0, numP=0; do{ printf("How much change is owed (in cents)?\n"); check = scanf("%d", &changeOwed); // returns 1 if the input is a number and returns 0 otherwise //Get's rid of any extra invisible characters if the input is a char/String do{ scanf("%c",&invisibleChar); }while(invisibleChar != '\n'); }while(check == 0...
Using the following code answer the next couple questions: #include<stdio.h> #include<stdlib.h> #include<string.h> /* Rewrite using a...
Using the following code answer the next couple questions: #include<stdio.h> #include<stdlib.h> #include<string.h> /* Rewrite using a pointer to char str[] */ void array_to_ptr () { int n=0, len; char str[ ] = "Hello World!"; len = strlen(str); for( n=0; n<len; n++) {     putc(str[n], stdout); } printf("\nlength = %d\n", n); } int contains (char * str, char c); int * makearray(int n); int main (void) { printf("Question #2 - array_to_ptr:\n"); array_to_ptr();   printf("\n------------------------------------\n\n"); printf("Question #3 - contains:\n"); printf("Test #1: "); if...
C CODE PLZ! Need all TO DO sections finished thanks #include <stdio.h> int main(int argc, char...
C CODE PLZ! Need all TO DO sections finished thanks #include <stdio.h> int main(int argc, char **argv) { const int BUF_LEN = 128; char str[BUF_LEN]; int i; char c; int is_binary; int d, n; /* Get the user to enter a string */ printf("Please enter a string made of 0s and 1s, finishing the entry by pressing Enter.\n"); for (i=0; i<BUF_LEN-1; i++) { scanf("%c", &c); if (c == '\n') { break; } str[i] = c; } str[i] = '\0'; /*...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT