简体   繁体   English

结构中用户的有限输入

[英]limited input from user in struct

help please this doesnt work properly请帮助,这不能正常工作

input输入
omayma.firstname: AAAAAAAAAAAAAAAAAAAAAAAAAAA omayma.firstname: AAAAAAAAAAAAAAAAAAAAAAAAAAA
omayma.lastname: BBBBBBBBBBBBBBBBBBBBBBBBBBBB omayma.lastname: BBBBBBBBBBBBBBBBBBBBBBBBBBBB
output: output:
omayma.firstname: AAAAAAAAAABBBBBBBBBB omayma.firstname: AAAAAAAAAABBBBBBBBBB
omayma.lastname: BBBBBBBBBB omayma.lastname: BBBBBBBBBB
expected output:预期 output:
omayma.firstname: AAAAA (10 A exatcly) omayma.firstname: AAAAA (10 A exatcly)
omayma.lastname: BBBBBB (10) omayma.lastname: BBBBBB (10)


typedef struct
{
    char firstname[10];
    char lastname[10];
} person;

int main()
{
    person omayma;
    printf("firstname : ");
    scanf("%10s", omayma.firstname);
    fflush(stdin);
    printf("lastname : ");
    scanf("%10s", omayma.lastname);
    fflush(stdin);
    puts(omayma.firstname);
    puts(omayma.lastname);
    return 0;
}

Suggestions to get your code to work as you probably expected it to.让您的代码按照您的预期工作的建议。

First, provide more space for names.首先,为名称提供更多空间。 space is cheap.空间便宜。 Go big (enough) in struct: Go 结构中的大(足够):

typedef struct
{
    char firstname[50];
    char lastname[50];
} person;

Second, if you have to use scanf() , make the follow on adjustments for larger buffers...其次,如果您必须使用scanf() ,请对更大的缓冲区进行以下调整...

scanf("%49s", omayma.firstname);// adds room for long names, 

Or, you can get rid of scanf() altogether with what may be a better alternative:或者,您可以完全摆脱scanf()可能是更好的选择:

fgets(omayma.firstname, sizeof omayma.firstname, stdin);
omayma.firstname[strcspn(omayma.firstname, "\n")] = 0;//remove newline
fgets(omayma.lastname, sizeof omayma.lastname, stdin);
omayma.lastname[strcspn(omayma.lastname, "\n")] = 0;//remove newline

printf("%s %s", omayma.lastname, omayma.lastname);



           

Third, fflush() is only used for output streams:第三, fflush()仅用于 output 流:

fflush(stdin);//delete this statement (everywhere)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM