Search code examples
cnewlinefgetsgetcharstrlen

How to remove multiple trailing newlines after fgets()?


#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>



int main()
{

int upper=0;
int digit=0;
int i=0;


char s[30];
char c;

printf("Enter sentence: ");
fgets(s, 30, stdin);

//s[strlen(s) - 1] = '\0';


while(c=getchar() && c!='\n')
{

  c = s[i];

     if(isupper(c))
    {
        upper++;
    }

     if(isdigit(c))
    {
        digit++;
    }


  i++;
}

printf("Number of upper case letters............... %d", upper);
printf("\n");
printf("Number of digits........................... %d", digit);
printf("\n");


printf("Program done. ");





return 0;
system("PAUSE");
}

How can I remove the multiple newlines after the fgets() ? I have tried implementing the following line after fgets()

s[strlen(s) - 1] = '\0';

but this does not work and my program does not run through all the code.

Without the code -----> s[strlen(s) - 1] = '\0';


Here is the Output:

Enter sentence: Whats UP 1234















Number of upper case letters............... 3
Number of digits........................... 4
Program done.
Process returned 0 (0x0)   execution time : 9.340 s
Press any key to continue.

As you can see my program is able to run however I have to press enter multiple times and there is a lot of newlines and then at the very end the program runs the last bit of code.

The program is suppose to count the number of upper case letters and digits in the string entered. Can someone please explain why this is happening ?


Solution

  • Thanks to Jongware:

    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    #include <string.h>
    
    
    
     int main()
     {
    
    int upper=0;
    int digit=0;
    int i=0;
    
    
    char s[30];
    char c;
    
    printf("Enter sentence: ");
    fgets(s, 30, stdin);
    
    //correction: getchar() has been removed from the while condition.
    while( c!='\n')
    {
    
     c = s[i];
    
      if(isupper(c))
     {
        upper++;
     }
    
     if(isdigit(c))
    {
        digit++;
    }
    
    
    i++;
    }
    
    printf("Number of upper case letters............... %d", upper);
    printf("\n");
    printf("Number of digits........................... %d", digit);
    printf("\n");
    
    
    
    
    return 0;
    system("PAUSE");
    }