c - 结构体和符号数组

标签 c string struct malloc buffer

你能帮我吗? 我的 char* station 有问题; 当我填补空白时,一切都很好,但是当我使用 printf("%d) 输入其电台:",i+1); 时。这是一个问题,我的意思是:我输入 chech-joch-chor-dsh-dsh 但我需要输入 chech joch chor dsh dsh(这些是电台的名称,它是一个例子)。所以它打印仅第一个单词,我不知道为什么..请检查一下...(我知道我需要释放我所拿的东西)。请解释一下为什么会这样,为什么是第一个?..给我一个提示..

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>



typedef struct info_bus_{
    int number;
    int begin;
    int end;
    char* stations;
    int time_working;
}info_bus;


int main()
{

    info_bus *b=NULL;
    int i,n;
    char buffer[128];
    printf("How many buses u have: ");
    scanf("%d",&n);

    b=(info_bus *)malloc(n*sizeof(info_bus));

    for(i=0;i<n;i++){
    printf("Input the number of a bus: ");
    scanf("%d",&(b+i)->number);

    printf("%d)Input when it starts to work: ",i+1);
    scanf("%d",&(b+i)->begin);

    printf("%d)Input when it  finishes to work: ",i+1);
    scanf("%d",&(b+i)->end);

        printf("%d)Input its stations: ",i+1);
        scanf("%127s", buffer);
        b[i].stations = (char*) malloc(strlen(buffer) + 1);
        strcpy(b[i].stations, buffer);

    printf("Input time working: ");
    scanf("%d",&(b+i)->time_working);
    }
    for (i=0;i<n;i++){
        printf("\n[%d].the number of a bus: %d",i+1,b->number);
        printf("\n[%d]. Begin at: %d",i+1,b->begin);
        printf("\n[%d]. Finishes at: %d",i+1,b->end);
        printf("\n[%d]. Stations: %s",i+1,b->stations);
        printf("\n[%d]. Time working: %d",i+1,b->time_working);
        printf("\n");
    }

    return 0;
}

但是当我使用gets()时 这是: enter image description here

最佳答案

    scanf("%127s", buffer);

遇到换行符后停止读取。如果您希望能够阅读多个单词,请使用 fgets() :

    fgets(buffer, sizeof buffer, stdin);

注意:如果有空间,fgets() 还将读取换行符。如果需要,您可以将其删除:

    buffer[strcspn(buffer, "\n")] = 0; /* to remove the newline */

一般情况下,即使对于其他输入,也应避免使用 scanf()。这很容易出错。请参阅:Why does everyone say not to use scanf? What should I use instead?

此外,malloc() 的转换也是不必要的。请参阅:What's wrong with casting malloc's return value?

关于c - 结构体和符号数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41315934/

相关文章:

c - INITCOMMONCONTROLSEX 未在此范围内声明

c - 需要更多这方面的信息!中止(核心转储)

java - 从引用中窃取位

c++ - 如何在 C++ 中检查字符串的开头

android - android 清除字符串中的值

python - 使用 SWIG 包装结构**(指向指针的指针)参数

python - 从类型 'MyStruct' 到类型 'void*' 的强制转换无效

c - 访问结构体中数组中的结构体

c - 如何输入客户 ID 作为仅包含数字的字符串,但使用字符,程序 C?

c# - 这个 C# 字符串格式是什么意思?