C++ Standard Input: accept multiple values

Introduction

We can accept multiple values from the standard input by separating them with multiple >> operators:

#include <iostream> 

int main() /*  w  w w . ja v  a  2s. co  m*/
{ 
    std::cout << "Please enter two numbers separated by a space and press enter: "; 
    int x = 0; 
    int y = 0; 
    std::cin >> x >> y; 
    std::cout << "You entered: " << x << " and " << y; 
} 

We can accept values of different types:

#include <iostream> 

int main() /*  w ww . j  a  v a 2 s  .  c  o m*/
{ 
    std::cout << "Please enter a character, an integer and a double: "; 
    char c = 0; 
    int x = 0; 
    double d = 0.0; 
    std::cin >> c >> x >> d; 
    std::cout << "You entered: " << c << ", " << x << " and " << d; 
} 



PreviousNext

Related