gpt4 book ai didi

c - 使用 C 编辑字符串并单独打印每个单词的程序

转载 作者:行者123 更新时间:2023-11-30 15:54:49 24 4
gpt4 key购买 nike

当我运行程序时,我不断收到错误段错误(核心转储)。

#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;
}

该程序的目标是将字符串 str[] 中的每个单词打印到控制台的新行上。我是一名初级程序员,这是一项作业,因此我必须使用这种类型的格式(不允许使用字符串库)。我只是想知道我哪里出了问题以及如何修复它。

最佳答案

嗯,我之前在你的另一个问题中见过这个程序... Function that reads each word in a string and prints each word on different line with C

您的循环中有错误:

while (s[nextindex] != ' ' || s[nextindex] != '\0')

使用&&,而不是||。该循环永远不会终止,因为两个条件中至少有一个始终为真。

然后你必须解决其他问题(未能检测到字符串结尾)。这样就可以了:

if( str[nextindex] != 0 ) {
str[nextindex] = '\0';
nextindex++;
} else {
nextindex = -1;
}

关于c - 使用 C 编辑字符串并单独打印每个单词的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719772/

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