Search code examples
c++streamcharcin

C++ cin char read symbol-by-symbol


I need to read symbol-by-symbol. But I don't know how to read until end of input. As exemple test system will cin>>somecharvariable m times. I have to read symbol-by-symbol all characters. Only m times. How I can do it?


Solution

  • If you want formatted input character-by-character, do this:

    char c;
    while (infile >> c)
    {
      // process character c
    }
    

    If you want to read raw bytes, do this:

    char b;
    while (infile.get(b))
    // while(infile.read(&b, 1)   // alternative, compare and profile
    {
      // process byte b
    }
    

    In either case, infile should be of type std::istream & or similar, such as a file or std::cin.