2016-12-24 85 views
0

你能帮助我吗? 我有一个问题char* station; 当我填补了我的空白,永恒的好处,但当我与printf("%d)Input its stations: ",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

+0

'scanf'的'%s'读作whilte-space分隔符。所以它不包含内容中的空格。 – BLUEPIXY

+0

@BLUEPIXY它应该如何解决? –

+0

另请参见[为什么获取函数如此危险以至于不应该使用?](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-应该不被使用) – e0k

回答

0
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?

+0

不要使用'gets()'。改用'fgets()'。你的问题的原因是'fgets()'会在换行符后停止读取输入。但以前的'scanf()'离开了一个换行符。这就是为什么你不应该混用'fgets()'和'scanf()'。 – usr

+0

拜托,看看我的问题,我已经把它变了。当我使用'gets()'时。它发生了它 –

+0

'“当它完成工作时输入:''和'”输入它的工作站:“'在同一行 –