I wanted to make a simple program in C that will in while loop get 10 strings user inputs and store them to file food.txt. But there is problem whenever I try to store again user input to variable inputFood. It also send error at 'strcpy(&allFood, inputFood);' Thread 1: Signal SIGABRT. Can anyone help please?
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main() {
int i = 0;
printf("Hello World!\n");
char * inputFood;
char allFood = {0};
FILE * fPointer;
fPointer = fopen("/Users/Antonio/Desktop/food.txt", "a");
while (i < 10){
i = i + 1;
scanf("%s", inputFood);
strcpy(&allFood, inputFood);
}
fputs(&allFood, fPointer);
fclose(fPointer);
}
Allocate memory for inputFood, for example 100 chars:
inputFood = malloc(100);
and make allFood an array, not a char:
char allFood[1000];
Because of that you will need to use strcat indstead of strcpy like this:
strcat(allFood, inputFood);
And scan the input food like this:
scanf("%99s", inputFood);
char * inputFood;
You need first allocate memory for it. use malloc/calloc
memory allocation.
And and
strcpy
use for copy string not char
.Also use fgets
instead scanf
to overcome buffer overflow issue.
Try something like this:
char inputFood[1024];
char allFood[1024];
while (i < 10){
i = i + 1;
fgets(inputFood, sizeof(inputFood), stdin);
if((strlen(allFood)+strlen(inputFood))<1024)
strncat(allFood, inputFood,strlen(inputFood));
}
you have to change many things in your program
1)allocate memory for inputFood
inputFood = malloc(100*sizeof(char));
2)as allFood is already a pointer, dont use &
in strcpy , and use
strcat`.
strcat(allFood, inputFood);
same goes for fputs
fputs(allFood, fPointer);
3) make allFood
a character array, as strcpy
and fputs
uses character pointers.
char allFood[1000];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.