在这段代码中,我让用户输入他们想要输入的字符数量.

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

int main(void) {

    // Ask the user to enter how many characters you want to write.
    printf("Enter how many characters you want to write. \n");
    int n;
    int itemsRead = scanf_s("%d", &n);

    if (itemsRead != 1) {
        // scanf didn't read the expected input, handle the error
        printf("Error: Input is not in the expected format.\n");
        return 1; // Return a non-zero value to indicate an error
    }
    
    // Clear the input buffer
    int c;
    while ((c = getchar()) != '\n' && c != EOF);

    char *string = NULL;
    string = (char *)malloc(n * sizeof(char));

    if (string != NULL) {
        printf("Enter the string \n");
        fgets(string, n, stdin);
        printf("string is: %s\n", string);
    }

    free(string);
    string = NULL;
}

问题是: 如果用户输入3个字符,然后try 输入3个字符,则只显示前2个字符.

推荐答案

请参考fgets documentation.

从给定的文件流中最多读取count-1个字符,并将它们存储在str指向的字符数组中.如果找到换行符,则解析停止,在这种情况下,字符串将包含换行符,或者如果出现文件结束.如果读取字节且未发生错误,则在紧接写入str的最后一个字符之后的位置写入一个空字符.

您的电话最多只能阅读n-1个字符.具有三个字节空间的char数组只能容纳两个字符的字符串,因为需要空终止符才能使其成为有效的字符串.

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

int main(void) {
    // Ask the user to enter how many characters you want to write.
    printf("Enter how many characters you want to write. \n");
    int n;
    int itemsRead = scanf_s("%d", &n);

    if (itemsRead != 1) {
        // scanf didn't read the expected input, handle the error
        printf("Error: Input is not in the expected format.\n");
        return 1; // Return a non-zero value to indicate an error
    }

    // Increment n by one to allow for the null terminator.
    ++n;
    
    // Clear the input buffer
    int c;
    while ((c = getchar()) != '\n' && c != EOF);

    char* string = NULL;
    string = (char*)malloc(n * sizeof(char));
    // Equivalent to:
    // string = (char*)malloc(n);
    // Because sizeof(char) == 1

    if (string != NULL) {
        printf("Enter the string \n");
        fgets(string, n, stdin);
        printf("string is: %s\n", string);
    }

    free(string);
    string = NULL;
}

C++相关问答推荐

为什么已经设置的值在C中被重置为for循环条件中的新值?

为什么在C中进行大量的位移位?

为什么GCC可以调用未定义的函数?

创建一个fork导致fget无限地重新读取文件

ESP32在vTaskDelay上崩溃

在传统操作系统上可以在虚拟0x0写入吗?

如何将常量char*复制到char数组

将uintptr_t添加到指针是否对称?

如何使用C for Linux和Windows的标准输入与gdb/mi进行通信?

如何识别Linux中USB集线器(根)和连接到集线器(根设备)的设备(子设备)?

为什么将函数名括在括号中会禁用隐式声明?

用C++实现余弦函数

For循环中的变量行为不符合预期.[C17]

按长度对argv中的单词进行排序

C将数组传递给函数以修改数组

运行时错误:在索引数组时加载类型为';char';`的空指针

OSDev--双缓冲重启系统

宏观;S C调深度

10 个字节对于这个 C 程序返回后跳行的能力有什么意义

Zig 中 C 的system函数的惯用替代方案