【问题标题】:Struct and a symbol array结构和符号数组
【发布时间】:2017-05-10 00:21:11
【问题描述】:

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

#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() 它是:

【问题讨论】:

标签: c string struct malloc buffer


【解决方案1】:
    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?

【讨论】:

  • 不要使用gets()。请改用fgets()。出现问题的原因是 fgets() 将在换行后停止读取输入。但是之前的scanf() 留下了一个换行符。这就是为什么你不应该混用 fgets()scanf()
  • 请看我的问题,我已经解决了。当我使用gets()。它发生在我身上
  • "Input when it finishes to work:""Input its stations:" 在同一行
  • 您必须读出换行符:只需在调用fgets() 之前使用getchar()。但我建议完全避免使用scanf()
  • 感谢您的帮助,使用了getchar()scanf(" %127[^\n]%*c", buffer);,现在可以使用了。但我也知道我不应该使用scanf().. 你能用fgets() 获得我的程序的正确代码吗?修理我:) 如果可以的话。谢谢,再帮忙一次
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多