简体   繁体   English

一个字符串有多个输入

[英]Multiple inputs to one string

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. 我想用C语言编写一个简单的程序,该程序将在while循环中获取10个字符串用户输入并将其存储到food.txt文件中。 But there is problem whenever I try to store again user input to variable inputFood. 但是,每当我尝试再次将用户输入存储到变量inputFood时,就会出现问题。 It also send error at 'strcpy(&allFood, inputFood);' 它还在“ strcpy(&allFood,inputFood);”处发送错误。 Thread 1: Signal SIGABRT. 线程1:信号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分配内存,例如100个字符:

inputFood = malloc(100);

and make allFood an array, not a char: 并将allFood设置为数组,而不是char:

char allFood[1000];

Because of that you will need to use strcat indstead of strcpy like this: 因此,您将需要像这样使用strcat代替strcpy:

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. 使用malloc/calloc内存分配。

And and 还有

strcpy use for copy string not char .Also use fgets instead scanf to overcome buffer overflow issue. strcpy用于复制字符串,而不是char 。还使用fgets代替scanf来解决缓冲区溢出问题。

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 1)为inputFood分配内存

inputFood = malloc(100*sizeof(char));

2)as allFood is already a pointer, dont use & in strcpy , and use strcat`. 2)由于allFood已经是一个指针,请不要在strcpy中使用& , and use strcat`。

 strcat(allFood, inputFood);

same goes for fputs fputs

fputs(allFood, fPointer);

3) make allFood a character array, as strcpy and fputs uses character pointers. 3)使allFood成为字符数组,因为strcpyfputs使用字符指针。

char allFood[1000];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM