提问人:Mohamed Taha 提问时间:9/14/2023 最后编辑:chqrlieMohamed Taha 更新时间:9/14/2023 访问量:54
无法理解 fgets 输出
Can't understand the fgets output
问:
在此代码中,我让用户输入他们想要输入的字符数。
#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 个字符,然后尝试输入 3 个字符,则仅显示前 2 个字符。
答:
2赞
Chris
9/14/2023
#1
请参阅 fgets
文档。
从给定文件流中读取最多 1 个字符,并将它们存储在 str 指向的字符数组中。如果找到换行符,则分析将停止,在这种情况下,str 将包含该换行符,或者如果出现文件末尾。如果读取了字节并且没有发生错误,则在写入 str 的最后一个字符之后的位置立即写入一个 null 字符。
您的呼叫最多读取字符。具有三个字节空间的 char 数组只能保存具有两个字符的字符串,因为需要 null 终止符才能使其成为有效字符串。n-1
#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;
}
上一个:从文件读取日期到链表
下一个:动态内存分配和指针
评论
fgets