I have a school assignment where I am supposed to create three functions. The functions are printFirstWord(), skipWords() and printWord().
Albeit not perfectly written, I have managed to make the printFirstWord function work and the other two functions mostly work fine.
However, in skipWords() I am supposed to return a pointer value of NULL if the amount of words that you wish to skip is greater than the amount of words in the string you input. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//Call the functions
void printFirstWord(char inputString[]);
char* skipWords(char sentence[], int words);
void printWord(char sentence[], int wordNumber);
int main()
{
printWord("I like to eat bunnies", 0); //Prints I
printWord("I like to eat bunnies", 1); //Prints like
printWord("I like to eat bunnies", 2); //etc
printWord("I like to eat bunnies", 3);
printWord("I like to eat bunnies", 4);
printWord("I like to eat bunnies", 5); //This should return NULL
printWord("I like to eat bunnies", 6); //This should return NULL
return 0;
}
//Function that prints only the first word of a string
void printFirstWord(char inputString[])
{
int i = 0;
//Removes initial non-alpha characters, if any are present
while (!isalpha(inputString[i]))
i++;
//Checks if the next input is alphabetical or is the character '-'
while (inputString[i] != ' ')
{
printf("%c", inputString[i]);
i++;
}
}
char* skipWords(char sentence[], int words)
{
int i = 0, wordCount = 0;
for(i = 0; wordCount < words; i++)
{
if(sentence[i] == ' ')
{
wordCount++;
}
}
//Can't get this to work, not sure how to return NULL in a function
if (words >= wordCount)
return NULL;
else
return &sentence[i];
}
void printWord(char sentence[], int wordNumber)
{
char *sentencePointer;
sentencePointer = skipWords(sentence, wordNumber);
if (sentencePointer != NULL)
printFirstWord(sentencePointer);
else if (sentencePointer == NULL)
printf("\nError. Couldn't print the word.\n");
}
Initially my problem was that the program constantly crashed but I added the last part of the printWord function and it stopped crashing. I expect this output:
Iliketoeatbunnies
Error. Couldn't print the word.
Error. Couldn't print the word.
This is the output I am receiving:
Error. Couldn't print the word.
Error. Couldn't print the word.
Error. Couldn't print the word.
Error. Couldn't print the word.
Error. Couldn't print the word.
Error. Couldn't print the word.
Pointers are my weak side and I feel like I have missed something crucial, I have been looking online and I haven't found any solution that fits me yet or atleast that I feel doesn't fit me.