gpt4 book ai didi

我的代码中 strncpy 中查找并打印最长单词的编译错误

转载 作者:行者123 更新时间:2023-11-30 21:35:26 27 4
gpt4 key购买 nike

我编写了一个程序来查找最长的单词并打印它。

我的代码是:

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

int MaxWord(char text[],char[]);

int main (void){
char text[1000];
char word[1000];
int max;

printf("geben Sie den Text bitte : ");
gets(text);
max=MaxWord(text,word);
printf("ist mit %d Zeichen das laengste wort im Text\n\n\n",max);
return 0;
}
int MaxWord(char text[], char word[])
{
char i;
int ctr=0;
int max=0;
int len;
char begin=0;

len=strlen(text);
for(i=0;i<len+1;i++)
{
if(isalpha(text[i]))
{
if(ctr==0)
{
begin=i;
}
ctr++;
}
else
{

if(ctr>max)
{
max=ctr;

}

ctr=0;
}
}
strncpy(word,begin,max);
printf("%s ",word);
return max;
}

错误是:

error #2140: Type error in argument 2 to 'strncpy'; expected 'const char * restrict' but found 'char'.

我该如何解决这个问题?

最佳答案

首先,您不应该使用 gets() 函数。使用 scanf 代替。另请参阅 http://www.cplusplus.com/reference/cstring/strncpy/

函数 strncpy 需要一个 const char* (以便您确信该函数不会修改源字符串)并且您向它传递一个字符。因此出现了错误。请修改您的函数以传入 char 指针。

您需要重新检查逻辑并通过传入正确的源字符串来修复 strncpy 调用。

关于我的代码中 strncpy 中查找并打印最长单词的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029894/

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