gpt4 book ai didi

c - 为什么我无法初始化指针变量并且无法使用gets?

转载 作者:行者123 更新时间:2023-11-30 18:27:09 24 4
gpt4 key购买 nike

我的书中有这段代码,但我尝试了很长时间来理解它,但我无法理解。因此,代码接受用户的输入,并打印每行的输出单词以及单词的大小。它还根据行打印输出。并且它排除任何 . ,! ETC.. 示例:

输入:

Hello, I am new here.
trying to learn.

输出:

Words typed on line number 1:
Hello(5)
I(1)
am(2)
new(3)
here(4)
Words typed on line number 2:
trying(6)
to(2)
learn(5)

此外,该代码可以在我 friend 的计算机上运行,​​但不能在我的计算机上运行。我不断收到错误消息,如下所示。你能给我解释一下吗?另外,为什么它对我不起作用?我该如何解决它?我尝试使用 fgets,但没有成功。

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

int main()
{
char str[10][81];
char* ptoken, * ptr;
int i = 0, maxstr = 0;
char* exclude = " .,!\t"; // I get an error message here (This entity cannot be initialized.)

printf("Enter the text you want on multiple lines\n");
printf("after you enter every thing pres ctrl+z and Enter \n\n");

while (gets(str[i])) // I get an error message here (The identifier gets cant be found).
{
str[i++];
maxstr++;
}

for (i = 0; i < maxstr; i++) {
printf("\n<< Words typed on line number %d> \n", i + 1);
ptr = str[i];
ptoken = strtok(ptr, exclude);
while (ptoken != NULL) {
printf("strlen(%s) = %d\n", ptoken, strlen(ptoken));
ptoken = strtok(NULL, exclude);
}
}

return 0;
}

最佳答案

char* 排除 = ".,!\t";//我在这里收到一条错误消息(此实体无法初始化。)

尝试修改字符串文字会产生未定义的行为。 const 可以防止您意外地执行此操作(即尝试通过指针写入的代码将无法编译,除非您删除 const 限定符,例如使用 throw )。

char const *exclude=".,!\t";

<小时/>

while (gets(str[i]))//我在这里收到一条错误消息(无法找到标识符 gets)。

gets 已被弃用,因为它很危险,可能会导致缓冲区溢出。

改为使用fgets

while (fgets(str[i],sizeof(str),stdin))

<小时/>

注意事项

printf("strlen(%s) = %d\n", ptoken, strlen(ptoken));

long int 中 strlen() 的返回类型 %ld

printf("strlen(%s) = %ld\n", ptoken, strlen(ptoken));

关于c - 为什么我无法初始化指针变量并且无法使用gets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934340/

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