Learing C++- -
Tag:
c++,
有关C++中while(cin >> s) 怎样让输入终止?
遇到的第一个问题,所以查询的资料多些,彻底明白就好:)
Often, especially at the start of semesters, I get a lot of questions about
how to write very simple programs. Typically, the problem to be solved is
to read in a few numbers, do something with them, and write out an answer.
Here is a sample program that does that:
#include
#include
#include
using namespace std;
int main()
{
vector v;
double d;
while(cin>>d) v.push_back(d); // read elements
if (!cin.eof()) { // check if input failed
cerr << "format error\n";
return 1; // error return
}
cout << "read " << v.size() << " elements\n";
reverse(v.begin(),v.end());
cout << "elements in reverse order:\n";
for (int i = 0; i<< v[i] << '\n';
return 0; // success return
}
Here are a few observations about this program:
- This is a Standard ISO C++ program using the standard library.
Standard library facilities are declared in namespace std in headers
without a .h suffix.
-
If you want to compile this on a Windows machine, you need to compile it as
a "console application".
Remember to give your source file the .cpp suffix or the compiler might think
that it is C (not C++) source.
-
Yes, main() returns an int.
-
Reading into a standard vector guarantees that you don't overflow some
arbitrary buffer.
Reading into an array without making a "silly error" is beyond the ability
of complete novices - by the time you get that right, you are no longer
a complete novice.
If you doubt this claim, I suggest you read my paper
"Learning Standard C++ as a New Language", which you can download from
my publications list.
-
The !cin.eof() is a test of the stream's format.
Specifically, it tests whether the loop ended by finding end-of-file
(if not, you didn't get input of the expected type/format).
For more information, look up "stream state" in your C++ textbook.
-
A vector knows its size, so I don't have to count elements.
-
This program contains no explicit memory management, and it does not
leak memory.
A vector keeps track of the memory it use to store its elements.
When a vector needs more memory for elements, is allocates more;
when a vector goes out of scope, it frees that memory.
Therefore, the user need not be concerned with the allocation and
deallocation of memory for vector elements.
-
for reading in strings, see
How do I read a string from input?.
-
The program ends reading input when it sees "end of file".
If you run the program from the keybord on a Unix machine "end of file"
is Ctrl-D.
If you are on a Windows machine that because of a bug
doesn't recognize an end-of-file character, you might prefer this slightly more
complicated version of the program that terminates input with the word "end":
#include
#include
#include
#include
using namespace std;
int main()
{
vector v;
double d;
while(cin>>d) v.push_back(d); // read elements
if (!cin.eof()) { // check if input failed
cin.clear(); // clear error state
string s;
cin >> s; // look for terminator string
if (s != "end") {
cerr << "format error\n";
return 1; // error return
}
}
cout << "read " << v.size() << " elements\n";
reverse(v.begin(),v.end());
cout << "elements in reverse order:\n";
for (int i = 0; i<< v[i] << '\n';
return 0; // success return
}
For more examples of how to use the standard library to do simple things
simply, see the "Tour of the Standard Library" Chapter of
TC++PL3 (available for download).
(2)Read from cin in a while loopThe standard C/C++ style for reading is to put the read operation in a while loop condition. If the read proceeds correctly, then the value is true. If there is an end-of-file (EOF) meaning that the end of the data has been reached, or if there is an error in reading, then the value returned is false and execution continues at the end of the loop.
Example -- Adding numbers in the input
int sum = 0;
int x;
while (cin >> x) {
sum = sum + x;
}
cout << sum;
Testing the value from an input operation
Using cin in a while loop is a very common style of programming.
* Produces a value. The input operation with cin not only reads values into variables, but it also produces a value. That's because >> is an operator that produces a value. This value can be tested in loops and ifs.
* true. The value of cin >> x is true if a value was read into x.
* false. The value of cin >> x is false if it was unable to read. There are several possible causes for a reading failure.
o EOF. When there is no more data, the EOF (End-Of-File) condition occurs. Every stream of input has an end so this is a normal event. It happens when reading a disk file and the end is reached. It's also possible to signal an EOF from the console by entering a special key combination, which depends on which operating system and C++ library you are using. Generally, you can use Control-Z followed by Enter to send an EOF from the keyboard. See End-Of-File (EOF).
o Bad data. The read may fail if the data isn't formatted correctly. For example, when trying to read a floating-point temperature and the user types "zero", the read will fail.
Use this pattern when reading. Another style, which is not generally used is Anti-idiom - Using cin in three places, instead of one.