如何同时接受字符串输入?

How to take string input simultaneously?

我正在做一个数据库基础项目 考虑一个结构

struct student
{ 
int rollno;
char full_name[20];
char address[50];
char birthmark[50];
};

如何接受这个输入

rollno 6

name john snow

address winterfell of north

birthmark swords wound all over

我试过的:

我试过了

scanf("%s",stringname),scanf("%[^\n]s",stringname),gets(stringname), fgets(buffer,size,stdin)fflush(stdin)。 总是有一些错误。 到目前为止 fgets 工作得很好,但我读过 ffush(stdin) is a wrong practice .

那么一个接一个地同时输入字符串(带空格)的方法应该是什么。

最好的方法是,从 fgets() 的输入中读取整行,然后在填充结构成员之前进行解析和验证。流程图可以看起来像

fgets(into the buffer) and the return is not NULL
if (integer)
store into rollno;
else 
copy the input string into corresponding member variable.

是的,fflush(stdin) 调用 undefined behavior,


(没有错误的代码和mcve,我们只能提供帮助)