Reputation: 2833
EDIT: solved it, turns out I should use %c
not %s
because foodSelect and foodSize are characters not strings :P thanks
I'm trying to pass 3 values to the function output
: foodChoice, foodSelect, foodSize (and foodOrderNum, and foodSubtotal but I haven't gotten around to that yet).
However, when I try to printf foodSelec
t, I get a segmentation fault, but when I try to print foodChoice
, I don't. When I try to printf foodSize
it just shows nothing.
source:
#include <stdio.h>
#include <string.h>
void question (char choice[]);
int output(char *foodChoice, char *foodSelect, char *foodSize);
void question (char choice[]) {
char choiceYesNo;
char *foodOptions;
char *foodChoice;
char *foodSelect;
char *foodSize;
int foodOrderNum = 0;
float foodSubtotal = 0;
switch (choice[0]) {
case 'f':
foodChoice = "Fish";
foodOptions = "(K- Haddock, T- Halibut)";
break;
case 'c':
foodChoice = "Chips";
foodOptions = "(C- Cut, R- Ring)";
break;
case 'd':
foodChoice = "Drinks";
foodOptions = "(S- Softdrink, C- Coffee, T- Tea)";
break;
}
printf("Do you order %s? (Y/N): ", foodChoice);
scanf("%c", &choiceYesNo);
printf("%s choice %s: ", foodChoice, foodOptions);
scanf("%s", &foodSelect);
printf("What size (L - Large, M - Medium, S - Small): ");
scanf("%s", &foodSize);
printf("How many orders do you want? (>=0): ");
scanf("%d", &foodOrderNum);
output(foodChoice, foodSelect, foodSize);
}
int output(char *foodChoice, char *foodSelect, char *foodSize) {
// printf("You ordered %s: %s - SIZE: %s amount ordered: , subtotal price: \n",
// foodChoice, foodSelect, foodSize);
printf("\n\n%s\n", foodSelect);
// printf("\n\n%s\n", foodSelect);
}
int main() {
question("chips");
}
Upvotes: 0
Views: 94
Reputation: 726509
This is because you pass &foodSelect
to scanf
, which is incorrect for C strings. You should pass foodSelect
instead, no ampersand.
You should also allocate sufficient space to store the values the users enter, and instruct scanf
on the max size of the buffer.
#define MAX_BUF 128
...
char foodSelect[MAX_BUF];
...
scanf("%127s", foodSelect);
Upvotes: 1