reading char by char
my question is a little bit strange, but how is it possible to read some string from keyboard char by char without using scanf()
and getchar()
only by using operator<<
, for example I wa开发者_Python百科nt to change every letter a
which I read by *
thanks in advance
char c;
std::string output;
while(std::cin >> c)
{
if(c == 'a')
c = '*';
output += c;
}
Depending on your purposes, you may find it adequate to do this:
#include <iostream>
#include <iomanip>
char c;
std::cin >> std::noskipws;
while (std::cin >> c)
std::cout << c == 'a' ? '*' : c;
See http://www.cplusplus.com/reference/iostream/manipulators/noskipws/ for further details of noskipws, which is crucial as otherwise operator>> will skip over spaces, tabs and newlines until it finds other characters to put in 'c', resulting in all the aforementioned whitespace characters being removed from your output.
Try writing out to a type of char.
char cReadFromStream;
stream >> cReadFromStream;
You cannot. operator <<
uses cooked inputs.
However, if you really meant you are looking for a solution using C++ iostreams and not C stdio functions, then use cin.get()
which is the C++ iostreams equivalent to getchar
.
精彩评论