2016-11-13 24 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"に複数の単語を格納できますが、2番目のループではジャンプします。複数の単語が文字列C

+4

C配列では、0から始まるインデックスを使用します。ループを0から '

+1

'main(){'は 'int main'ですか? –

+0

文字列にscanf()を使用しないでfgets()を使用してください:http://www.cplusplus.com/reference/cstdio/fgets/ – Gaulthier

答えて

-1

最初に:C配列がゼロベースなので、ループをゼロ(i = 0)で開始する必要があります。

これは、最後のscanf()stdinバッファに改行を残すためです。入力バッファをフラッシュする組み込み関数(fflush())がありますが、時には、何らかの理由でそれは動作しませんので、私たちは、カスタムclean_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(); 
} 

注:次のコードを試すことができます。

+0

今すぐ作業!ありがとうございました。私は、問題はあなたの関数clean_stdin()で解決されたと思う;ありがとうございました ! –

+0

問題ありません。名前の最後に '\ n'を削除する行を追加しました。 – karliwson

関連する問題