0

Here is a function for some code im working on in C. Right now it accepts 2 different user inputs and stores them as city and distance. What I want is for the user to input only once. For example "Enter the city name and distance from previous city: Arlington 200". I need to separate that string into values for city and distance. I think I need to use tokens but im not sure how.

void addCity ()
{
char city[30];
int distance;

printf("Enter city name : ");
scanf("%s",city);
printf("Enter distance from previous city: ");
scanf("%d",&distance);
printf("The city has been added.\n");

if(root == NULL){
root = (struct node *) malloc( sizeof(struct node) );
strcpy(root->city, city);
root->distance = distance;
root->next = NULL;
}
else
{

struct node *currentNode = root;
struct node *newNode = (struct node *) malloc( sizeof(struct node) );
while(currentNode->next!=NULL)
{
currentNode = currentNode->next;
}

strcpy(newNode->city, city);
newNode->distance = distance;

currentNode->next = newNode;
}
}

1 Answers1

0

You can prompt for both at once:

printf("Enter the city name and distance from previous city: ");
scanf("%s %d",city, &distance);
dbush
  • 205,898
  • 23
  • 218
  • 273