我尝试在程序的字符串数组中输入多个字符串,使用了以下代码:
scanf("%80[^\r\n]", strings[i]);
fgets(string[i], MAXLEN, stdin);
还使用了一个自定义函数:
int getString(char s[]) {
char ch;
int i=0;
while( (ch = getchar()) != '\n' && ch != EOF ) {
s[i] = ch;
++i;
}
s[i] = '\0';
fflush(stdin);
return i;
}
但无法获取包含空格的多个字符串输入
函数gets()
以前对我有用,但是由于已经过时,找不到替代方法
这就是它被使用的地方:
int getString(char s[]) {
char ch;
int i=0;
while( (ch = getchar()) != '\n' && ch != EOF ) {
s[i] = ch;
++i;
}
s[i] = '\0';
fflush(stdin);
return i;
}
struct vechileData
{
char vechileType[MAXLEN];
int begin_month;
int end_month;
double price;
} data[5];
int main(int argc, char const *argv[])
{
printf("Input Vechile data: \n");
int i=0;
while(i < 5) {
printf("Input vechile Type : \n");
fgets(data[i].vechileType, MAXLEN, stdin);
printf("Input begin month : \n");
scanf("%d", &data[i].begin_month);
printf("Input end monhth : \n");
scanf("%d", &data[i].end_month);
printf("Input price : \n");
scanf("%lf", &data[i].price);
++i;
}
printf("Input Vechile Type to display information about the vechile : \n");
char vech[MAXLEN];
fgets(vech, MAXLEN, stdin);
i=0;
while(i < 5) {
if (strcmp(vech,data[i].vechileType) == 0)
{
printf("vechileType: %s\n", data[i].vechileType);
printf("Begin month: %d\n", data[i].begin_month);
printf("End month: %d\n", data[i].end_month);
printf("Price : %lf\n", data[i].price);
}
++i;
}
return 0;
}
在运行时,它似乎跳过了下一个输入到字符串语句。
fflush()
是一个不好的主意,因为刷新只对输出流有明确定义。 - unwindgets
的替代方案是fgets
。 - Some programmer dudegets()
已被弃用就放弃它,而是应该因为它很危险而放弃使用。 - Oswald