Open In App

Read a string after reading an integer

In this article, we will discuss how to read a string after reading an integer.

Program 1:



Below is the program that inputs a string with spaces just after taken an input of an integer




// C++ program that inputs a string
// with spaces just after taken an
// input of an integer
  
#include <iostream>
#include <string>
using namespace std;
  
// Driver Code
int main()
{
    int t = 0;
    cin >> t;
  
    string s;
  
    // Taking input with spaces
    getline(cin, s);
  
    cout << "You entered : "
         << s << "\n";
  
    return 0;
}

Output:



Explanation:

Program 2: In C++, the ignore() function accounts for nullifying the extra newline character which is generated by pressing “enter”. Below is the C++ program illustrating the use of the function ignore():




// C++ program to illustrate the use
// of the function ignore()
  
#include <iostream>
#include <string>
using namespace std;
  
// Driver Code
int main()
{
    int t = 0;
    cin >> t;
  
    // Adding the ignore()
    cin.ignore();
  
    string s;
    getline(cin, s);
  
    cout << "You entered : "
         << s << "\n";
  
    return 0;
}

Output:


Article Tags :