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

标签 c loops for-loop fgets c-strings

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

相关文章:

java - 为什么这个 for 循环是无限的?

php - 多个嵌套循环无法按预期工作

c - 为什么线程函数的参数应该在堆中?

c - C具体是如何运行的?

c - 从不同文件访问静态数组的 'strdup'

Ruby 每个循环都没有为每个元素完成

c - 为什么 linkat 需要路径名而不是文件描述符?

linux - 如何将 file1 的每一列附加到 file2 的特定字段并制作新的输出文件?

C++:访问冲突

r - for循环在r列表中的所有数据框中进行方差分析测试