Program that edits string and prints each word individually with C
- by Michael_19
I keep getting the error segmentation fault (core dumped) when I run my progam.
#include<stdio.h>
#include<stdlib.h>
int nextword(char *str);
int main(void)
{
char str[] = "Hello! Today is a beautiful day!!\t\n";
int i = nextword(str);
while(i != -1)
{
printf("%s\n",&(str[i]));
i = nextword(NULL);
}
return 0;
}
int nextword(char *str)
{
// create two static variables - these stay around across calls
static char *s;
static int nextindex;
int thisindex;
// reset the static variables
if (str != NULL)
{
s = str;
thisindex = 0;
// TODO: advance this index past any leading spaces
while (s[thisindex]=='\n' || s[thisindex]=='\t' || s[thisindex]==' ' )
thisindex++;
}
else
{
// set the return value to be the nextindex
thisindex = nextindex;
}
// if we aren't done with the string...
if (thisindex != -1)
{
nextindex = thisindex;
// TODO: two things
// 1: place a '\0' after the current word
// 2: advance nextindex to the beginning
// of the next word
while (s[nextindex] != ' ' && s[nextindex] != '\0')
nextindex++;
str[nextindex] = '\0';
nextindex++;
}
return thisindex;
}
The goal of the program is to print each word in the string str[] to the console on a new line. I am a beginning programmer and this is an assignment so I must use this type of format (no string library allowed). I just would like to know where I went wrong and how I can fix it.