C++ - Quitting a program

[亡魂溺海] 提交于 2019-12-10 19:58:50

问题


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.


回答1:


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




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/4746980/c-quitting-a-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!