Simplicity
Simplicity

Reputation: 48916

C++ - Quitting a program

In the C++ Without Fear: A Beginner's Guide That Makes You Feel Smart book in chapter(8), part of a code trying to display a text file is the following:

while(1)
{
    for(int i=1; i <= 24 && !file_in.eof(); i++)
    {
        file_in.getline(input_line,80);
        std::cout<<input_line<<std::endl;
    }

    if(file_in.eof())
    {
        break;
    }

    std::cout<<"More? (Press 'Q' and ENTER to quit.)";
    std::cin.getline(input_line,80);
    c=input_line[0]; // <<<<<<
    if(c=='Q'||c=='q')
    {
        break;
    }
}

The part I'm not getting here is:

c=input_line[0];

I think it is put to read 'Q' or 'q'. But, why using this form (Array)? And, isn't there a way to read 'Q' or 'q' directly?

I tried std::cin>>c; but seemed to be incorrect.

Any ideas?

Thanks.

Upvotes: 3

Views: 1476

Answers (4)

Albertino80
Albertino80

Reputation: 1093

NON-STANDARD solution, but works on windows platforms.

you can use getch() function defined in conio.h example:

#include <conio.h>
...
char c = getch();

bye

Upvotes: -4

Simon Richter
Simon Richter

Reputation: 29586

You are getting the first character from the "array" into which the input line has been written.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

I tried std::cin>>c; but seemed to be incorrect.

That's correct, if c is a char.

You're right; reading an entire line just to extract a single character is bizarre. I recommend a book from this list.

Upvotes: 3

Kiril Kirov
Kiril Kirov

Reputation: 38143

Because input_line is string ( array from chars), so input_line[0] gets the first letter - this is in case, that the user write "quit" or "Quit", not just "Q"

std::cin >> c; would be correct, if you enter just one char and press Enter

Upvotes: 3

Related Questions