在这段代码中,我让用户输入他们想要输入的字符数量.
#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个字符.