Aleander said:
Can you explain me this, too?
------ foo.cpp ------
#include <iostream>
#include <ios>
using namespace std;
typedef char String20[20];
int main()
{
int times;
String20 name;
cout << "How many times do you want to repeat the loop?: ";
// -----------------
// The user should enter: some integer value + "Enter",
if (!(cin >> times))
{
cerr << "Illegal times" << endl;
return 1;
}
// ..................
// Sample-1
// For instance, the user enters: "357" + "Enter".
// 'times' is of int type.
// So, in this case cin reads until non-digit in the input, i.e., cin read '3', '5', '7'.
// After that cin sees "Enter" (i.e., '\n') and stops.
// Important! Now input stream contains '\n'.
// ..................
// Sample-2
// For instance, the user enters: "169abc" + "Enter".
// 'times' is of int type.
// So, in this case cin reads until non-digit in the input, i.e., cin read '1', '6', '9'.
// After that cin sees 'a' and stops.
// Important! Now input stream contains 'abc\n'
// -----------------
-------------------
//
http://www.cppreference.com/cppio/ignore.html
// istream &ignore( streamsize num=1, int delim=EOF );
// The ignore() function is used with input streams.
// It reads and throws away characters until num characters
// have been read (where num defaults to 1) or until
// the character delim is read (where delim defaults to EOF).
-------------------
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << endl;
cout << "Insert your Name: ";
cin.getline(name, 20);
// ---------------------------
// Situation analysis
//
// -------------------------
// Sample-1: "357" + "Enter"
// -------------------------
// Case-1. Without "cin.ignore(numeric_limits<streamsize>::max(),'\n');" above.
// Our input stream already contains '\n'.
// So, cin.getline() reads 0 characters into name and that why it is not waiting for our entering name.
// In this case name = "". (Note. '\n' is not put into name.)
// Case-2. With "cin.ignore(numeric_limits<streamsize>::max(),'\n');" above.
// '\n' after "357" has been ignored.
// Our input stream is empty.
// So, cin.getline() is waiting for entering name.
//
// -------------------------
// Sample-1: "169abc" + "Enter"
// -------------------------
// Case-1. Without "cin.ignore(numeric_limits<streamsize>::max(),'\n');" above.
// Our input stream already contains 'abc\n'.
// So, cin.getline() reads 'abc' into name and that why it is not waiting for our entering name.
// In this case name = "abc". (Note. '\n' is not put into name.)
// Case-2. With "cin.ignore(numeric_limits<streamsize>::max(),'\n');" above.
// 'abc\n' after "169" has been ignored.
// Our input stream is empty.
// So, cin.getline() is waiting for entering name.
// ---------------------------
cout << "name = " << name << endl;
return 0;
}