Question

In: Computer Science

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;
}

Solutions

Expert Solution

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;
}


Related Solutions

Fix the C++ code to count the number of inversions using the given array. The answer...
Fix the C++ code to count the number of inversions using the given array. The answer is 8 inversions, but I am only getting 6 inversions. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <iostream> using namespace std; int mergeInversion(int arr[], int l, int m, int r) {     // size of the two arrays     int n1 = m - l + 1;     int n2 = r - m;     // create temporary arrays     int L[n1];     int R[n2];     // Copy the...
Translate this algorithm to code on C compare(char array[ ]) word = split(array, " "); //gets...
Translate this algorithm to code on C compare(char array[ ]) word = split(array, " "); //gets the first word before the blank space if word == Hello { print("I am saying hello"); }else if (word == Bye) print("I am saying goodbye"); } Example--------------------- char array = "Hello Ana"; compare(array); char array1 = "Bye Ana" compare(array1); result "I am saying hello" "I am saying goodbye"
How can i bubble sort a sentence in a char array in c++ This is the...
How can i bubble sort a sentence in a char array in c++ This is the prototype of the function: char* sort(char string[], int numOfWords, int lengthOfWord); This is the testing code in the main file: char words[] = "CAT FAT BAT HAT RAT"; printf("Before sort: t%s\n";words); char result = sort(words; 5; 3); printf("After sort : t%s\n"; result); Expected output: Before sort: CAT FAT BAT HAT RAT After sort: BAT CAT FAT HAT RAT
I am using IntelliJ IDEA with JavaFX to build a travel expensive calculator, but somehow it...
I am using IntelliJ IDEA with JavaFX to build a travel expensive calculator, but somehow it wouldn't calculate total expensive? It was working until I add the TextFieldListener because I need to make sure user only input either mile driven or airfareCost. Please help me figure out what I did wrong. import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import...
I am using NetBeans IDE Java to code and I am seeking comment to the code...
I am using NetBeans IDE Java to code and I am seeking comment to the code as well (for better understanding). Magic squares. An n x n matrix that is filled with the numbers 1, 2, 3, …, n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value. Write a program that reads in 16 values from the keyboard, displays them in a 4...
I am trying to tokenize a string using a function by passing the char string[] and...
I am trying to tokenize a string using a function by passing the char string[] and char *pointer[100]. While I have working code inside the int main(), I am having trouble actually declaring the parameters for the function. I know how to pass the char array (char string[]), but not how to pass the char pointer array (char *pointer[100]). This is my code below: int main() {    // Declare variables    char str[] = "this is a test only...
Send an element from 2d array to a function using pointer to pointer. c++ I am...
Send an element from 2d array to a function using pointer to pointer. c++ I am having an issue with being able to send specific elements to the swap function. #include <iostream> using namespace std; void swap(int **a, int **b){    int temp = **a;    **a=**b;    **b=temp; } void selSort(int **arr, int d){    for(int i =0; i<d-1; i++){        int min = *(*arr+i);        int minin = i;        for(int j =i+1; j<d; j++){...
c++ I need a code that will fill an array size of 1000, an array of...
c++ I need a code that will fill an array size of 1000, an array of size 2000, and an array size of 10000, with random int values. Basically like this: array1[1000] = filled all with random numbers array2[2000] = filled all with random numbers array3[10000] = filled all with random numbers C++ no need for print
for C program 10 by 10 char array. char 0-9 as rows and char a-j as...
for C program 10 by 10 char array. char 0-9 as rows and char a-j as collumns.
Explain this code: The structure used is max heap using array. C++ (i is the index...
Explain this code: The structure used is max heap using array. C++ (i is the index of the element to be deleted) void del(int i) {    int left,right,temp;    arr[i]=arr[n-1];    n=n-1;    left=2*i+1; /*left child of i*/    right=2*i+2; /* right child of i*/    while(right < n)    {        if( arr[i]>=arr[left] && arr[i]>=arr[right] )            return;        if( arr[right]<=arr[left] )        {            temp=arr[i];            arr[i]=arr[left];   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT