我无法正确接受用户的输入 [英] i can't take input from user properly
问题描述
我曾经使用过 scanf();但是visual studio告诉我这不安全,当我使用 fgets();它只输入前两个输入,第三个被忽略
i used to work with scanf(); but visual studio tells me it's not safe, when i use fgets(); it only inputs the first two input and the third one is ignored
void main() {
char c=' ';
char s[20];
char sen[40];
fgets(&c, sizeof(c), stdin);
fgets(s, sizeof(s), stdin);
fgets(sen, sizeof(sen), stdin);
system("pause");
}
这里它实现了前两个,第三个 fgets 完全被忽略为什么??以及在 c 中从用户那里获取输入的良好做法是什么?
here it implements the first two and the third fgets is totally ignored WHY?? and what are the good practices in taking input from user in c?
推荐答案
fgets 将在缓冲区内存储空终止符和回车符.所以你应该确保缓冲区足够大来存储你的数据+空终止符+回车.如果你使用像 c 这样的单个字符,那么它应该是一个大小为 3 的数组. Character+0+\n对数组进行零初始化也是一种很好的做法.
fgets will store the null terminator along with the carriage return inside the buffer. SO you should make sure the buffer is large enough to store your data+null terminator+carriage return. If you are taking a single character like c, then it should be an array of size 3. Character+0+\n It's also good practice to zero initialise your arrays.
#include <stdio.h>
int main() {
char c[3] = {0};
char s[20] = {0};
char sen[40] = {0};
fgets(c, sizeof(c), stdin);
fgets(s, sizeof(s), stdin);
fgets(sen, sizeof(sen), stdin);
return 0;
}
并使用 int main 而不是 void main.
And use int main instead of void main.
如果你确实想在 fgets 中使用单个字符输入,你可以通过阅读自己清除输入流,直到从流中拉回回车.
If you do want to use a single character input in fgets, you can clear the input stream yourself by reading until carriage return is pulled from the stream.
#include <stdio.h>
int main() {
char c;
char s[20] = {0};
char sen[40] = {0};
fgets(&c, sizeof(c), stdin);
while(getchar() != '\n'); //read until carriage return
fgets(s, sizeof(s), stdin);
fgets(sen, sizeof(sen), stdin);
return 0;
}
这篇关于我无法正确接受用户的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!