reading char by char

2019-09-09 17:20发布

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 want to change every letter a which I read by * thanks in advance

标签: c++
4条回答
干净又极端
2楼-- · 2019-09-09 18:07

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.

查看更多
别忘想泡老子
3楼-- · 2019-09-09 18:07

Try writing out to a type of char.

char cReadFromStream;

stream >> cReadFromStream;
查看更多
走好不送
4楼-- · 2019-09-09 18:19

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.

查看更多
劫难
5楼-- · 2019-09-09 18:22
char c;
std::string output;


while(std::cin >> c)
{
   if(c == 'a')
      c = '*';

   output += c;

}
查看更多
登录 后发表回答