mardi 10 octobre 2023

how to use std::cin.ignore()

how to use std::cin.ignore() to clear all the unread data from cin.

The program reads a list of words until the user ends the input by pressing the ctrl+D as to mark the end of input.Then I like to read a char. But the cin statement didn't work. So I just cleared all error flags as ctrl+D will put cin in error state, but still it didn't work so I used ignore() to read all unread characters but the program still didnt work as expected. So it will be greatful if some one can tell how to solve this particular situation as c++ primer book as lot of programs which has similar while loop.

#include <iostream>
#include <vector>
#include <limits>

int main(){
    std::vector<std::string> svec;
    std::cout << "Enter the list of words : \n";
    std::string word;
    while(std::cin >> word)
        svec.push_back(word);
    std::cin.clear(); 
    std::cin.ignore(std::numeric_limits<std::streamsize>::max());
    std::cin.clear(); 
    
    char ch;
    std::cout << "\nEnter the character : ";
    std::cin >> ch;

    std::cout << "no of words : " << svec.size() << "\n and the char entered : "<< ch << std::endl;
    return 0;
}

output:

Enter the list of words : 
one two three
Enter the character : no of words : 3
and the char entered : 

by casting the value of ch to int we get the following output

Enter the list of words : 
one two three
Enter the character : no of words : 3
and the char entered : 0

Aucun commentaire:

Enregistrer un commentaire