#include<stdio.h>
#include <conio.h>
#include <string.h>
float final(float);
//声明要在代码中使用的变量的结构。
struct tag
{
int n;
int age[50];
int dist;
char name[1][50];
char stfrom[50];
char stto[50];
}var;
void main()
{
int i;
float apcost,f;
char str[50];
char name[10][50];
printf("Enter the number of tickets:\n");
scanf(" %d",&var.n);// Total number of tickets
for(i=0;i<var.n;i++)// This loop will run as many number of tickets.
{
// taking inputs of names with spaces and ages.
printf("Enter name:\n");
scanf(" %[^\n]%*c",name[i]);
strcpy(var.name[i], name[i]);
printf("Enter age:\n");
scanf(" %d",&var.age[i]);
}
printf("\nEnter Station from:\n");
scanf(" %[^\n]%*c",var.stfrom);
printf("Enter Station to:\n");
scanf(" %[^\n]%*c",var.stto);
printf("Enter the distance:\n");
scanf(" %d",&var.dist);
apcost = (var.dist * 3) * var.n;
f = final(apcost);
printf("---------------------------------------------------------------------\n");
printf("---------------The Final Bill-------------------------\n\n\n");
printf("Number of tickets purchased:%d\n\n",var.n);
printf("Names and ages of persons respectively:\n");
for(i=0;i<var.n;i++)
{
puts(var.name[i]); //Here the station is getting printed instead of name.
printf("\n%d\n",var.age[i]);
}
printf("\n\nStation From:");
puts(var.stfrom);
printf("\n\nStation to:");
puts(var.stto);
printf("\n\nTotal cost of tickets:%f\n\n",apcost);
printf("--------------------\n");
printf("The final cost after adding 12% tax:%f\n",f);
}
float final(float apcost)
{
float j,k;
j= (0.12 * apcost);
k= apcost + j;
return k;
}
当我运行代码并输入票数为2时,我输入的第二个名称不会打印在最终帐单中,而是打印var.stto。
答案 0 :(得分:0)
问题出在你的结构定义中:
struct tag
{
int n;
int age[50];
int dist;
char name[1][50];
char stfrom[50];
char stto[50];
}var;
name的定义被静态定义为包含1个名称,并且当您尝试写入stfrom
时,您的代码正在访问name[2]
。要解决此问题,您需要使name
成为动态变量(使其数组大小为0)并使用malloc
为结构分配正确的空间量。
例如:
struct tag
{
int n;
int age[50];
int dist;
char stfrom[50];
char stto[50];
char name[][50];
};
...
struct tag *var = malloc(sizeof(struct tag) + 50*num);
其中num
是要购买的门票数量