简体   繁体   中英

Counting number of lines, words and characters while taking input as a string in loop

I am trying to solve the following problem in C language. The input is taken as strings and user enters each string in new line. While user enters "END" , the program must stop taking input and should display the number of lines , words and characters. To achieve this I wrote the following code:

#include<stdio.h>  
#include<string.h>
void main(){
 char a[100], b = {'E', 'N', 'D'};
 int i, k, word = 0, chr = 0, line = 0 ;
 printf("Enter paragraph (enter END to stop)\n");
 gets(a);
 k = strcmp(a,b);
 while (k != 0 ){
    line++;
    for (i = 0; a[i] != '\0'; i++){
        if (a[i] == ' ')
           word++;
        else 
            chr++;
     }
     gets(a);
     k = strcmp(a,b);

   }
  printf("%d %d %d\n", line, word, chr );
 }

In the above code I assumed that the user is using only space button to give spaces between words. The problems was as soon as I give first input I get an error message saying program has stopped working.

I am not able to see whether my logic is wrong or my usage of syntax is wrong.

In the variable declaration

 char a[100], b = {'E', 'N', 'D'};

b is declared as a scalar. This will lead to Segmentation Fault in strcmp(a,b) because both arguments of strcmp() must be pointers.

It should be

 char a[100], b[] = "END";

you have to add [] to make b an array and you don't need to put each characters separately. Using string literal style initialization also have the compiler add terminating null-character so that you can pass that to strcmp() safely.

One more note is that you shouldn't use gets() , which has unavoidable risk of buffer overrun, deprecated in C99 and removed from C11. You can use fgets() , which can specify the length of the buffer, instead. fgets() stores newline character while gets() doesn't, so you have to remove that manually. This can be done like this, for example.

char a[100];
char *lf;
fgets(a, sizeof(a), stdin);
if ((lf = strchr(a, '\n')) != NULL) *lf = '\0';

Also I suggest you should use standard int main(void) in hosted environment instead of void main() , which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use non-standard signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM