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++开发者_如何学JAVA)
{
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.
Because input_line
is string ( array from char
s), 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
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.
You are getting the first character from the "array" into which the input line has been written.
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
精彩评论