I'm trying to scan in a single line input and storing it in a struct. I'm not sure if I am storing it wrong or I am printing it wrong. I'm not sure on how to use scanf
with for
loops since I never done it before not to mention C likes to overwrite stuff. So I wasn't sure on how to approach this.
This is something I put together but when I print I get junk numbers. I was intending to maybe use pointers but my professor won't let us use it. Which is why I'm having trouble.
EDITED
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 3
#define MAXTRIP 6
struct stop
{
float cost;
float time;
};
struct trip
{
char Dest_letter;
int stop_num;
struct stop leg[MAX];
};
int main(void)
{
int trip_num, index, i;
struct trip travel[MAXTRIP];
printf("Enter number of trips: ");
scanf("%d", &trip_num);
printf("Please enter destination letter/number of stops and cost/length of each stop:\n");
for (index = 0; index < trip_num; index++)
{
scanf("%c %d", &travel[index].Dest_letter, &travel[index].stop_num);
for ( i=0; i < travel[index].stop_num; i++)
scanf("%f %f", &travel[index].leg[i].cost, &travel[index].leg[i].time);
}
for (index =0; index < trip_num; index++)
{
printf("Trip:%d \nDestination Letter:%c", index+1, travel[index].Dest_letter);
for (i=0; i < travel[index].stop_num; i++)
printf("Cost:%.2f \nLength:%.2f", travel[index].leg[i].cost, travel[index].leg[i].time);
}
}
You have your printing loop inside your reading loop. It is trying to print out all of the trip information after reading the first one in.
Edit: The trouble here is that the way
scanf
handles single characters is kinda unintuitive next to the way it handles strings and numbers. It reads the very next character from standard in, which is probably a newline character from when you finished typing the previous input. Then it proceeds to try and read an integer, but instead it finds the letter you had intended to be consumed by the%c
. This causesscanf
to fail and not initializestop_num
.One way around this may be to read in a string instead.
scanf
will start reading the string at the first non-whitespace character and stop reading it at the first whitespace character. Then just take the first character from the buffer you read the string into.scanf()
is used to get a value for runtime and used in control string