2016-11-13 44 views
0
#include <stdio.h> 
#include <conio.h> 

#define STUD 3 

struct students { 
    char name[30]; 
    int score; 
    int presentNr; 
} student[STUD]; 

void main() { 
    for (int i = 1; i <= STUD; i++) { 
    printf("Name of the student %d:\n", i); 
    scanf("%[^\n]s", student[i].name); 

    printf("His score at class: "); 
    scanf("%d", &student[i].score); 

    printf("Number of presents at class: "); 
    scanf("%d", &student[i].presentNr); 
    } 
    getch(); 
} 

嗨,大家好! 我想在一個結構中存儲一個學生的名字和他在課堂上的分數。 在第一個循環中,我可以在變量「name」中存儲多個單詞,但在第二個循環中,它會跳過。字符串中的多個字C

+4

在C數組中使用從零開始的索引。讓循環從0運行到'

+1

應該'void main(){'是'int main'? –

+0

不要使用scanf()作爲字符串,使用fgets():http://www.cplusplus.com/reference/cstdio/fgets/ – Gaulthier

回答

-1

首先:您需要從零開始循環(i = 0),因爲C數組是從零開始的。

這就是說,我猜你的問題是因爲最後的scanf()stdin緩衝區中留下了換行符。你可以試試下面的代碼:

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

#define STUD 3 

struct students { 
    char name[30]; 
    int score; 
    int presentNr; 
} student[STUD]; 

void clean_stdin(void) 
{ 
    char c; 
    do c = getchar(); while (c != '\n' && c != EOF); 
} 

int main() { 
    for (int i = 0; i < STUD; i++) { 

    printf("Name of the student %d:\n", i + 1); 
    fgets((char*)&student[i].name, 30, stdin); 

    // Remove the line break at the end of the name 
    student[i].name[strlen((char*)&student[i].name) - 1] = '\0'; 

    printf("His score at class: "); 
    scanf("%d", &student[i].score); 

    printf("Number of presents at class: "); 
    scanf("%d", &student[i].presentNr); 

    // cleans stdin buffer 
    clean_stdin(); 
    } 

    getchar(); 
} 

注:有一個內置函數(fflush())刷新輸入緩衝區,但有時,由於某種原因,這是行不通的,所以我們使用自定義clean_stdin()功能。

+0

現在的工作!謝謝。我認爲,問題是用你的函數clean_stdin()解決的。再次感謝你 ! –

+0

沒問題。剛剛添加了一行以刪除名稱末尾的'\ n'。 – karliwson

相關問題