【发布时间】:2017-12-13 17:59:54
【问题描述】:
我有一个学校作业,我应该在其中创建三个函数。函数是 printFirstWord()、skipWords() 和 printWord()。
尽管写得并不完美,但我已经设法让 printFirstWord 函数正常工作,而其他两个函数大部分工作正常。
但是,在 skipWords() 中,如果您希望跳过的单词数量大于您输入的字符串中的单词数量,我应该返回一个指针值 NULL。这是我的代码:
#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");
}
最初我的问题是程序经常崩溃,但我添加了 printWord 函数的最后一部分并且它停止了崩溃。我期望这个输出:
Iliketoeatbunnies
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.
Error. Couldn't print the word.
Error. Couldn't print the word.
指针是我的弱点,我觉得我错过了一些重要的东西,我一直在网上寻找,但我还没有找到任何适合我的解决方案,或者至少我觉得不适合我。
【问题讨论】:
-
输入将是单个空格分隔的字符串?
-
什么是单词?为什么要发布图片而不是好的 Unicode 文本?
-
@coderredoc 输入将是一个包含多个单词的句子,该函数应该指向用户选择的单词(int words)。基本上我所做的是,对于出现的每一个空格,程序都会知道另一个单词已经开始。这很简单,但它完成了现在需要做的事情。
-
提示:当到达字符串末尾时,您的某些循环需要退出。
-
@lemonslayer 在复制格式化文本时,我有时会发现先将其粘贴到纯文本编辑器中,然后从那里复制/粘贴,最后添加目标所需的任何格式会更容易。