Question

The following code should count the simple assignments("=") in a text written by an user (improvised C code) by reading letter by letter. I am trying to do a check as well, if the operator is not the sought one, e.g. "less then or equal to" operator - "<=".

The output should show up when CTRL+Z is reached(EOF). When run, the output is always 0 and no text could be written in advance - the output is directly displayed.

There are no errors popping up in the Error list of the compiler. Could it be that the scanf is not inside the loop or maybe the variable "i" is not properly or not at all assigned to the text array?

    int count=0, i;
    char text[100];

    printf("\nEnter a program code - to end please hit enter followed by CTRL+Z:\n");
    scanf("%c", &text)!=EOF;
    for(i=0; i<strlen(text); i++){
       if (text[i]=='=') 
         count++;
       else if(text[i+1]=='=')
         continue;
       else if(text[i-1]=='<'||text[i-1]=='>'||text[i-1]=='!'||text[i-1]=='=')
         continue;
     }         
     printf("\nNumber of '=' operators are: %d\n", count);
Was it helpful?

Solution

A reasonable solution could be the following:

      while(gets(text)){
       for(i = 0; i < strlen(text); i++)
      {
            if (text[i]=='=') 
    {      
if(text[i+1]=='=')
     continue;
if(text[i-1]=='<'||text[i-1]=='>'||text[i-1]=='!'||text[i-1]=='=')
     continue;
            count++;
    }
      } 

EOF could be an option with scanf("%s", &text)!=EOF inside the while loop. Also note that the counter should be placed after the last if statement in order to check properly. Otherwise it will count != <= etc. operators all together with the simple "=".

OTHER TIPS

First of all, %c reads one character, and not a string.

Then, the !=EOF does nothing.

Then, strlen(text) invokes undefined behaviour since text has not been properly initialized (only its first character has been).

Finally, once you fix all the above problems, text[i-1] and text[i+1] will lead to undefined behaviour at the start and the of the string.

scanf("%c", &text)!=EOF;

Should be

scanf("%s", text);

scanf expects a pointer and text is still (decays) into pointer, the comparision with EOF makes non sense.

Also, calculate strlen before the for loop (not on each iteration)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top