gpt4 book ai didi

C 程序在程序结束时返回随机字符? (最后一个功能)

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:02 25 4
gpt4 key购买 nike

这段代码只是我在摆弄指针并看到它们的用途,因为我是一个初学者。不过,我在代码末尾遇到了一个问题。它应该在一个新行上显示每个单词,但是在最后一个单词之后它只显示一组随机字符。

#include <stdio.h>
#include <string.h>

void printWord(char *start);
char *nextWord(char *start);


void main()
{
int i = 0;
char location[200] = "7825 CREEK VALLEY SACRAMENTO 95828 CA";
char *ptr;
...

第一个函数打印前 3 个单词

// 3. instead of printing characters (using putchar) until a '\0', printWord 
// prints characters until a space ' '
puts("First Word");
printWord(location);

puts("Second Word");
printWord(location+5);

puts("Third Word");
printWord(location+11);
puts("");

第二个函数引起了我的问题,评论尽可能地解释了它。

    ...
// starting from the first character in the input string, each call to
// "nextWord" should return the next word in the string
// e.g. if the input string is "Hi there everyone" :
// first call to nextWord should return the address of the letter 't' of
// "there"
// second call to nextWord should return the address of the first letter
// 'e'of "everyone"
// third call to nextWord should return NULL

ptr = location;
while(ptr)
{
// instead of printing characters (using putchar) until a '\0',
// printWord prints characters until a space ' '
printWord(ptr);
printf("\n");
ptr = nextWord(ptr);
}


}

这个函数可以正常工作

void printWord(char *start)
{
for(; *start != ' '; start++){
putchar(*start);
}
putchar('\n');
}

但是这个给我带来了问题......

char *nextWord(char *start)
{
int i=0;
for(; *start != '\n'; start++){
if(*start == ' '){return(start+1);}
else if(*start == '\0'){return NULL; }

}
}

最佳答案

只需按如下方式编辑 printWord() 函数:

void printWord(char *start)
{
for (; *start != ' '; start++) {
if (*start == '\0') { break; }
putchar(*start);
}
putchar('\n');
}

你没有处理行尾情况

关于C 程序在程序结束时返回随机字符? (最后一个功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48477759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com