3

コンソールから入力を読み取り、それを文字の配列に入れる必要があります。次のコードを記述しましたが、次のエラーが発生します:「セグメンテーション違反」

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

int main() {

    char c;
    int count;
    char arr[50];

    c = getchar();
    count = 0;
    while(c != EOF){
        arr[count] = c;
        ++count;
    }


    return (EXIT_SUCCESS);

}
4

3 に答える 3

9
#include <stdio.h>
#include <stdlib.h>
int main() {
    char c;                /* 1. */
    int count;
    char arr[50];
    c = getchar();         /* 2. */
    count = 0;
    while (c != EOF) {     /* 3. and 6. and ... */
        arr[count] = c;    /* 4. */
        ++count;           /* 5. */
    }
    return (EXIT_SUCCESS); /* 7. */
}
  1. cintである必要があります。getchar()は、有効な文字とEOFを区別するためのintを返します
  2. 文字を読む
  3. その文字をEOFと比較します。異なる場合は7にジャンプします。
  4. その文字を配列arr、要素に入れますcount
  5. 配列の次の要素に「別の」文字を配置する準備をします
  6. 1で読み取った文字のEOFを確認します

ループを通過するたびに異なる文字を読み取る必要があります。(3.、4.、5。)

また、予約したスペースより多くの文字を配列に入れることはできません。(4.)

これを試して:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int c;                 /* int */
    int count;
    char arr[50];
    c = getchar();
    count = 0;
    while ((count < 50) && (c != EOF)) {    /* don't go over the array size! */
        arr[count] = c;
        ++count;
        c = getchar();     /* get *another* character */
    }
    return (EXIT_SUCCESS);
}

編集

配列にキャラクターが入ったら、何かしたいと思うでしょう?したがって、プログラムが終了する前に、それらを印刷するための別のループを追加します。

/* while (...) { ... } */
/* arr now has `count` characters, starting at arr[0] and ending at arr[count-1] */
/* let's print them ... */
/* we need a variable to know when we're at the end of the array. */
/* I'll reuse `c` now */
for (c=0; c<count; c++) {
    putchar(c);
}
putchar('\n'); /* make sure there's a newline at the end */
return EXIT_SUCCESS; /* return does not need () */

文字列関数printf()を使用しなかったことに注意してください。文字列ではないため、使用しませんarrでした。これは、(必然的に)0(NUL)を持たない文字の単純な配列です。NULを含む文字配列のみが文字列です。

NULをarrに入れるには、ループを50文字に制限するのではなく、49文字に制限して(NUL用に1スペース節約)、最後にNULを追加します。ループの後に、

arr[count] = 0;
于 2009-09-10T20:48:14.267 に答える
6
#include <stdio.h>
#include <stdlib.h>

int main() {

    int c;
    int count;
    int arr[50];

    c = getchar();
    count = 0;
    while( c != EOF && count < 50 ){
        arr[count++] = c;
        c = getchar();
    }


    return (EXIT_SUCCESS);

}

whileループの&&カウントが50未満であることに注意してください。これがないと、arrバッファをオーバーランする可能性があります。

于 2009-09-10T20:14:34.957 に答える
4

ちょっとした提案があります。プログラムに2回
含める代わりに、 whileループを次のように 変更します。c = getchar();

while( (c = getchar()) != EOF && count < 50 ){
        arr[count++] = c;
}
于 2012-06-30T20:09:37.637 に答える