我注意到我的短代码中有一个奇怪的错误。这个脚本的目的是创建一个结构数组,其中包含一些关于汽车的信息
("Struct Car Car1: char brand[50], char model[50], int ccm, int hp, int kw, char[50]")
在运行脚本之后,直到第一个实例被填充为止,一切都很好,但是当变量i
增加了1时,换行符从我要求用户提供";品牌;以及";型号";。很抱歉这是我第一次使用structs。谢谢你的帮助。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#define _CRT_SECURE_NO_WARNINGS
#define MAX 10
int main() {
struct Car {
char brand[50];
char model[50];
int ccm;
int hp;
int kw;
char wheel[50];
};
struct Car Car1;
strcpy(Car1.brand, "Skoda");
strcpy(Car1.model, "Octavia");
Car1.ccm = 1960;
Car1.hp = 170;
Car1.kw = 114;
strcpy(Car1.wheel, "215/75R18");
printf("The car's brand is: %sn", Car1.brand);
printf("The model is: %sn", Car1.model);
printf("The volume of the engine is %d ccmn", Car1.ccm);
printf("It has %d horsepowern", Car1.hp);
printf("The car has %d kwsn", Car1.kw);
printf("You can put: %s wheels on itn", Car1.wheel);
struct Car car_arr[MAX];
int i;
for (i = 0; i < MAX; i++) {
printf("Enter details of a car: %dn", i+1);
printf("n");
printf("Enter the brand: ");
fgets(car_arr[i].brand, sizeof car_arr[i].brand, stdin); //Brand
car_arr[i].brand[strcspn(car_arr[i].brand, "n")] = ' ';
printf("Enter the model: ");
fgets(car_arr[i].model, sizeof car_arr[i].model, stdin); //Model
car_arr[i].model[strcspn(car_arr[i].model, "n")] = ' ';
printf("Enter the parameters of the wheel: ");
fgets(car_arr[i].wheel, sizeof car_arr[i].wheel, stdin); //Wheel
car_arr[i].wheel[strcspn(car_arr[i].wheel, "n")] = ' ';
printf("Enter the volume of the engine in ccms: ");
scanf_s("%d", &car_arr[i].ccm);
printf("Enter the horsepower: ");
scanf_s("%d", &car_arr[i].hp);
printf("Enter the amount of kilowatts: ");
scanf_s("%d", &car_arr[i].kw);
}
return 0;
}
以上评论回答了您的问题,但附带说明:你可以通过使用";typedef";与";结构";。
typedef struct{int x1;long x2;double etc;}my_type;