如何在C中输入和扫描多个字符 [英] How to enter and scan multiple chars in c
问题描述
我想输入多个printfs,但是我没有机会输入. 我只能输入1,但之后它才结束程序.我尝试了do,但没有用
I want to enter multiple printfs but i dont get opportunity to enter. I can enter only 1, but after that it just ends the programme.I tried with do while but it didnt work
int main()
{
int number;
char username[30]="";
char fullName[30]="";
char password[30]="";
printf("Do you want to log in(1) or register (2)? \n");
scanf("%d",&number);
if (number==2)
{
printf("username : ");
scanf("%s",&username);
printf("Full name : ");
scanf("%s",&fullName);
printf("Password : ");
scanf("%s",&password);
printf("Repeat password : ");
scanf("%s",&password);
}
return 0;
}
推荐答案
我只能输入1,但之后它会结束程序.
I can enter only 1, but after that it just ends the programme.
Of course, as the code has if (number==2)
@Scadge
如果输入"2"
,请考虑以下事项:
If you enter "2"
, consider the following:
scanf("%s",&fullname);
不会将空格或其他空白保存到fullname
中.输入全名(例如"John Doe")会将"John"
保存到fullname
,将"Doe"
保存到password
.
scanf("%s",&fullname);
will not save spaces or other white-spaces into fullname
. Entering a full name like "John Doe" will save "John"
into fullname
and "Doe"
into password
.
避免使用scanf()
.
使用fgets()
读取用户输入,而不是使用scanf()
来读取用户输入.这是可以处理各种输入问题的辅助功能的绝佳机会.
Rather than use scanf()
to read user input, read user input with fgets()
. This is a fine opportunity for helper functions that can handle various input issues.
int read_int(const char *prompt) {
if (prompt) fputs(prompt, stdout);
fflush(stdout); // insure output is written before asking for input
char buffer[40];
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return NULL;
}
int i;
if (sscanf(buffer, "%d", &i) == 1) {
return i;
}
// TBD - what should code do if invalid data entered. Try again?
}
char *read_line(char *dest, sizeof size, const char *prompt) {
if (prompt) fputs(prompt, stdout);
fflush(stdout); // insure output is written before asking for input
char buffer[size * 2 + 1]; // form buffer at _least 1 larger for \n
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return NULL;
}
size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') buffer[--len] = '\0';
if (len >= size) {
// input too big - how do you want to handle this?
TBD_Code();
}
return strcpy(dest, buffer);
}
现在使用这2个帮助器功能进行简洁的用户输入
Now use these 2 helper functions for clean user input
// printf("Do you want to log in(1) or register (2)? \n");
// scanf("%d",&number);
number = read_int("Do you want to log in(1) or register (2)? \n");
...
// printf("username : ");
// scanf("%s",&username);
read_line(username, sizeof username, "username : ");
// printf("Full name : ");
// scanf("%s",&fullName);
read_line(fullName, sizeof fullName, "fullName : ");
可以添加其他代码来检查文件结尾,超长行,int
范围测试等.
Additional code could be added to check for end-of-file, extremely long lines, int
range testing, etc.
这篇关于如何在C中输入和扫描多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!