User Input

In C++, you can use cin to get user input. The syntax is pretty similar to outputting variables.

Example:
                                
                                    #include <iostream> 
                                    using namespace std;
                                    
                                    int main() {
                                        int number;
                                        cout << "Enter a number: ";
                                        cin >> number;
                                        cout << "You entered: " << number << endl;
                                        return 0;
                                    }
                                
                            

Input of integers and decimals are separated by whitespace, but not characters. For example: char c;cin>>c; with can get you c=' ' if a space is what you entered.

Cute Little Tricks With Cin

cin.ignore() ignores some input. It takes one or two arguments, meaning it accepts one or two variables or constants. The first argument is an integer of type std::streamsize and must be included, this is the number of characters that cin will ignore. The second argument is a character and is optional. It is the character that will make cin start reading input again if seen in input.

Example:

#include<iostream>
#include <limits> //for numeric_limits<streamsize>::max()
using namespace std;
int main(){
  int x;
  cin.ignore(numeric_limits<streamsize>::max(),'\n');//numeric_limits<streamsize>::max() means infinity (in this context only)
  cin>>x;
  char c;
  cin.ignore(5,'\n');//ignore 5 characters or \n is met
  cin>>c;//inputs 'c' since '\n' is met
  cout<<x<<" "<<c;
  cin.ignore(5,'\n');
  cin>>c;//this time, 5 characters are read without a newline
  cout<<c<<endl;
  return 0;
}
/*
Input:
74389749438 47389274287 4328974923 473289473 
100
c     x
Output:
100 cx

*/
                      

Curious about how to make your program do the same thing forever? You'll need loops!