0

このプログラムはファイルを読み込み、ユーザーに表示する行数を入力するように求めます。行数が表示された後、さらに行を印刷するか、または Return キーを押して終了するかをユーザーに再度求めるプロンプトが表示されます。

改行や改行をキャプチャして終了するのに苦労しています。戻るボタンを押してもプログラムは終了しませんが、ASCII 値を入力すると終了します (10 は改行の 10 進数です)。

Enterキーが押されたときにプログラムを終了させたい。

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

int main (int argc, char *argv[])
{
    FILE *file = fopen(argv[1], "r");
    int newLineCounter, currentChar, numOfLines;

    printf("enter a number of lines of lines to be displayed\n");
    scanf("%d", &numOfLines);

    while ((currentChar = fgetc(file)) != EOF)
    {
        printf("%c", currentChar);    //print character

        if (currentChar == '\n')      //check for newLine character
            newLineCounter++;  

        if (numOfLines == newLineCounter)
        {
            printf("\nenter a number of lines to be displayed or just return to quit\n"); 
            scanf("%d", &numOfLines);

            newLineCounter = 0; 

            //supposed to exit if return is pressed
            if (numOfLines == '\n')  //????why does this only execute when the decimal value of newline is entered
                return 0;
        }
    }

    //printf("%d lines in the text file\n", newLineCounter);

    fclose(file);

    return 0;
}
4

2 に答える 2

-1

scanf のフォーマット文字列を正しく理解していないようです。%d は明示的に「整数を探しています」という意味です。これが、改行文字の ASCII 数字表現のみを取得する理由です。

新しい行を文字としてキャプチャする場合は、scanf を %c にする必要があります。次に、整数の文字表現を実際の整数に変換する単純な関数を作成できます。ただし、%c も 1 文字しか読み取ることができないため、実際に使用したいのは %s で、一連の文字 (文字列とも呼ばれます) を読み取ることです。受け入れる最大桁数。文字配列と String の間にはほとんど違いはありません。具体的には、文字列は null で終了する文字配列です (文字列の最後の要素は null 文字 \0 です)。

簡単に言えば、文字ポインタを使用し、scanf フォーマット文字列を %s に変更してください。次に、最初の文字が \n かどうかを確認します。そうでない場合は、文字列を整数に変換し、その値を使用して行を読み取ります。

以下は、このソリューションを反映するためにわずかに変更されたコードです。

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

int main (int argc, char *argv[])
{
    FILE *file = fopen(argv[1], "r");
    int newLineCounter, currentChar, numOfLines;

    printf("enter a number of lines of lines to be displayed\n");
    scanf("%d", &numOfLines);

    while ((currentChar = fgetc(file)) != EOF)
    {
        printf("%c", currentChar);    //print character

        if (currentChar == '\n')      //check for newLine character
            newLineCounter++;  

        if (numOfLines == newLineCounter)
        {
            char* input;
            printf("\nenter a number of lines to be displayed or just return to quit\n"); 
            scanf("%s", &input);

            if( input[0] == '\n' || input[0] == '\0' ){
                return 0;
            } else {
                numOfLines = atoi( input );
            }
            newLineCounter = 0; 

            //supposed to exit if return is pressed
//            if (numOfLines == '\n')  //????why does this only execute when the decimal value of newline is entered
//                return 0;
//        }
    }

    //printf("%d lines in the text file\n", newLineCounter);

    fclose(file);

    return 0;
}
于 2012-08-18T02:04:14.633 に答える