0

It took me a while to be able to compile and run this program, and now I'm getting a "segmentation fault" message. What have I done wrong?

Here's my code:

#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <ctype.h>
#include <string.h>

int get_index(string s);

int letter; 
int word;
int sentence; 

int main(void)
{ 
    string text = get_string("Text: ");
  
    for (int i = 0, n = strlen(text); i += 1, n; i++)
    {
        if (isalpha(text[i]))
        {
            letter++;
        }
        if (isspace(text[i]))
        {
            word++;
        }
        if (text[i] == '.' || text[i] == '!' || text[i] == '?')
        {
            sentence++;
        }
    }

    float l = letter / word * 100;
    float s = sentence / word * 100;
    float index = 0.0588 * 1 - 0.296 * 2 - 15.8;
    int grade = round(index);
    
    if (index < 1)
    {
        printf("Before Grace 1\n"); 
    }
    if (index >= 16)
    {
        printf("Grade 16+\n");
    }
    else
    {
        printf("Grade %d\n", grade);
    }
}
1

Have a look at your evaluation condition for your loop:

i += 1, n

The net result of this condition is simply that i will get incremented by 1 each loop. The comma operator has the lowest precedence so the ", n" is essentially irrelevant here. Because the loop already increments i each turn, the loop will ultimately increment i by 2 every iteration for infinity (eventually causing a segmentation fault).

A correct condition would probably just look like:

i < n
0

Sentox is right, I would add something quite elementary too, look at the following statements,

float l = letter / word * 100;
float s = sentence / word * 100;

and make sure that word is not zero, it is good practice to initialize the variables, what happens if there are no spaces?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .