c-如何提出一系列问题



这是我的代码。我想让它按顺序问我问题。但每当我输入自己的选择并输入自己的名字时,我都无法进一步询问。如何处理?

#include <stdio.h>
#include <stdlib.h>
int new_acc();
int main(){
int one=1, two=2, three=3, four=4, five=5, six=6, seven=7, new_account;
printf("-----WELCOME TO THE MAIN MENU-----nn");
printf("%d. Create new accountn",one);
printf("Enter you choice: ");
if (scanf("%d",&one)){
new_account = new_acc(); // calling a function
}
return 0;
}
int new_acc(){
int id; char name;
printf("Enter your name: ");
scanf("%cn",&name);
printf("Enter your ID card number: ");
scanf("%dn",&id);    
return 0;
}

如果在为MAIN MENU键入nubmer后键入Enter,换行符将保留在缓冲区中
然后,is通过%c读取为名称
之后,如果您键入(例如(字母表作为名称,它将阻止它读取数字id
为了避免这种情况,可以在%c前面放一个空格,使其跳过换行符
此外,您不必在读取名称和id后跳过,因此应在%c%d之后删除scanf()中的n

int new_acc(){
int id; char name;
printf("Enter your name: ");
scanf(" %c",&name); /* add space and remove n */
printf("Enter your ID card number: ");
scanf("%d",&id);    /* remove n */
return 0;
}

顺便说一下,上面的代码将只允许一个字母表作为名称。要支持多字符名称(不含空格字符(,应使用指定长度的char%s数组。

int new_acc(){
int id; char name[1024];
printf("Enter your name: ");
scanf(" %1023s",name); /* don't use & here, and size limit is buffer size - 1 (-1 for terminating null character) */
printf("Enter your ID card number: ");
scanf("%d",&id);    
return 0;
}

如果您想支持带有空格字符的名称,可以使用%[n](读到换行符(而不是%s

int new_acc(){
int id; char name[1024];
printf("Enter your name: ");
scanf(" %1023[^n]",name);
printf("Enter your ID card number: ");
scanf("%d",&id);    
return 0;
}

似乎您想在这方面使用面向对象的编程范式。为此,您应该用struct定义一个"对象",并用它保存新帐户:

#define MAX 50
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Account {
int id;
char name[MAX];
};
struct Account new_acc();
int main(){
int choice;
struct Account new_account;
printf("-----WELCOME TO THE MAIN MENU-----nn");
printf("1. Create new accountn");
printf("Enter you choice: ");
scanf("%d",&choice);
switch(choice) {
case 1:
new_account = new_acc();
break;
default:
printf("Not a valid optionn");
return 1;
}
return 0;
}
struct Account new_acc(){
char name[MAX];
int id;
struct Account new;
printf("Enter your name: ");
scanf("%cn",name);
printf("Enter your ID card number: ");
scanf("%dn",&id);    
strcpy(new.name, name);
new.id = id;
return new;
}

请注意,因为此代码很容易受到缓冲区溢出的影响。另外,我编辑了您在main中对选项的检查,因为如果成功读取任何值,scanf都会返回1。

使用此代码我对进行了一点修改

int new_acc(){
int id; char name[10];
printf("Enter your name: ");
scanf("%s",name);
printf("Enter your ID card number: ");
scanf("%d",&id);    
return 0;
}