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

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...
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.
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...
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];   ...
I want Algorithim of this c++ code #include<iostream> using namespace std; int main() { char repeat...
I want Algorithim of this c++ code #include<iostream> using namespace std; int main() { char repeat = 'y'; for (;repeat == 'y';){ char emplyeename[35]; float basic_Salary,EPF, Dearness_Allow, tax, Net_Salary , emplyee_id; cout << "Enter Basic Salary : "; cin >> basic_Salary; Dearness_Allow = 0.40 * basic_Salary; switch (01) {case 1: if (basic_Salary <= 2,20,00) EPF = 0; case 2: if (basic_Salary > 28000 && basic_Salary <= 60000) EPF = 0.08*basic_Salary; case 3: if (basic_Salary > 60000 && basic_Salary <= 200000)...
Write a code using c# Maximum Sub Array.
Write a code using c# Maximum Sub Array.
C++ Bank Account Error Fix, full code. I am using Dev-C++ to Compile and Execute. The...
C++ Bank Account Error Fix, full code. I am using Dev-C++ to Compile and Execute. The project is below, I have supplied the code and I'm getting an error in SavingsAccount.h file. 17   5   C:\Users\adam.brunell\Documents\Classes\C++\Week4\SavingsAccount.h   [Error] 'SavingsAccount::SavingsAccount(std::string, double, double)' is protected A.Assume i.SavingsAccount: Assume an Interest Rate of 0.03 ii.HighInterestSavings: Assume an Interest Rate of 0.05, Minimum Balance = $2500 iii.NoServiceChargeChecking: Assume an Interest Rate = 0.02, Minimum of Balance = $1000 iv.ServiceChargeChecking – Assume account service charge = $10,...
(In C language) Given a two-dimensional char array, how do I encode it into a one...
(In C language) Given a two-dimensional char array, how do I encode it into a one dimensional integer array? For example: char arr [8][8] = {{1,1,1,1,1,1,1,1}, {1,0,0,0,1,0,0,1}, {1,0,1,0,1,1,0,1}, {1,0,1,0,0,0,0,1}, {1,0,1,1,1,1,0,1}, {1,0,0,0,0,0,0,1}, {1,0,1,0,1,0,1,1}, {1,1,1,1,1,1,1,1}} into int arr2 [8] I know this problem requires bit-shifting but I am unsure how. It also needs to be as efficient as possible. Thanks!
Please use c++ and follow the instruction I have written my own code but somehow I'm...
Please use c++ and follow the instruction I have written my own code but somehow I'm confused during the process I cannot figure out how to finish this lab, I need help. Write a program that allows user to input four floating-points values and then prints the largest. It must use functions max2 (given below) to determine the largest value. Feel free to use additional functions, but you are not required to do so. Hint: main will call max2 three...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT