Yordan Borisov
Yordan Borisov

Reputation: 1652

terminate char of text

My question is simple in the OOP languages but in the language C is not so simple. When the user enter some text data in the console and we set for terminate char for an example ESC (the text data is multiline and we do not know when the end is).

So my question is how to read a text from the console and if the user press esc to break the loop where we read the text data?

Here is some code:

    printf("Enter the source here(press ESC) : \n");
char buffer[1000][1000];
int counter = 0;
while(1)
{
    if (fgets(buffer[counter],sizeof(buffer[counter]),stdin))
    {
        counter++;
    }

}

Upvotes: 0

Views: 148

Answers (4)

Artur
Artur

Reputation: 7257

I think you do not really need to read up to that much of data from the console. Maybe try considering putting data to a file and read it from the file then.

Upvotes: 0

Kornel Kisielewicz
Kornel Kisielewicz

Reputation: 57555

You can manually get a single character using getchar() -- use that in a loop that checks if the character is ESC. However, if you're writing anything bigger, it's better to use a dedicated library like pdcurses.

Upvotes: 0

MAK
MAK

Reputation: 26586

I think the proper way to read in multiple lines of text is to terminate the input with an EOF character. In Windows I think it is ctrl+Z (I'm not sure), on unix-like systems it is ctrl+D. Many input functions in C automatically recognize it as a terminator (e.g. scanf and gets), or you can read character by character and explicitly the input char.

Upvotes: 1

cnicutar
cnicutar

Reputation: 182649

The easiest way would be to require the user to "end the file" by presing C-z or C-d. Alternatively:

#define ESC 27 /* But not always. */

int ch;
while ((ch = getc(stdin))) {
    if (ch == ESC)
        break;

    /* ... */
}

Since input is usually cooked, it's harder thank you think: the user can keep entering stuff after pressing escape.

Using ncurses for this can be an alternative. Then again, what's wrong with pressing C-d ?

Upvotes: 2

Related Questions