How to retrieve the next character from the stream without consuming it in C++

1 Answer

0 votes
#include <iostream>
#include <cctype> 

int main() {
    std::cout << "Please enter a word: ";
    std::cout.flush(); // clear the input stream (cin) as preparation for the next input 

    std::cin >> std::ws; // skip the leading whitespace include newline
    int ch = std::cin.peek(); // retrieve the next character from the stream without consuming it
    
     std::cout << "ch = " << (char)ch << '\n';

    if (ch == EOF) {
        return 1;
    }

    std::string str;
    std::cin >> str;
    std::cout << "You entered the word: " << str << '\n';
}
  
  
 
/*
run:
 
Please enter a word: Programming
ch = P
You entered the word: Programming

*/

 



answered Nov 22, 2024 by avibootz
edited Nov 22, 2024 by avibootz

Related questions

1 answer 116 views
1 answer 172 views
1 answer 187 views
1 answer 159 views
1 answer 159 views
...