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?
-
Try putting it into a string. – Mike D Oct 06 '11 at 19:14
-
Are you reading until end of input, *m* times, or are you reading *m* amount of symbols? – Thomas Matthews Oct 06 '11 at 19:21
-
or look into `istream::get(char* buffer, size_t len, char delimiter)` and `istream::read(char* buffer, size_t len)` if you want all bytes including whitespace and newlines – Mooing Duck Oct 06 '11 at 19:24
3 Answers
There are several ways to read one character at a time until you have read them all, and none of them is necessarily the best.
Personally, I’d go with the following code:
char c;
while (cin.get(c)) {
// Process c here.
}
If you only need to read m
characters, consider using a for
loop:
char c;
for (unsigned int i = 0; i < m && cin.get(c); ++i) {
// Process c here.
}
This runs the loop as long as two conditions are fulfilled: (1) less than m
characters have been read, and (2) there are still characters to read.
However, both solutions have a drawback: they are relatively inefficient. It’s more efficient to read the m
characters in one go.
So first allocate a big enough buffer to store m
chars and then attempt to read them:
std::vector<char> buffer(m);
cin.read(&buffer[0], m);
unsigned total_read = cin.gcount();
Notice the last line – this will tell you whether m
characters have been actually read.

- 530,221
- 131
- 937
- 1,214
-
This solution doesn't read m amount of symbols or it doesn't repeat reading until EOF, m times. – Thomas Matthews Oct 06 '11 at 19:25
-
+1 for the update, especially covering the EOF case in the `for` loop. – Thomas Matthews Oct 06 '11 at 19:33
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
.

- 464,522
- 92
- 875
- 1,084
-
For reading raw bytes (symbos), the `cin.read` method is usually more efficient, at the very minimum it uses less function calls. – Thomas Matthews Oct 06 '11 at 19:36
-
@ThomasMatthews: Thanks, I thought about that, too -- I added the alternative version. – Kerrek SB Oct 06 '11 at 19:42
Try this:
#include <iostream>
using std::cin;
using std::cout;
int main(int argc, char *argv[])
{
char ch;
unsigned m = 10;
while (cin && m--) {
cin.read(&ch, sizeof(ch));
cout << ch;
}
return 0;
}

- 627
- 1
- 9
- 16
-
1
-
This solution doesn't read *m* amount of symbols or it doesn't repeat reading until EOF, *m* times. – Thomas Matthews Oct 06 '11 at 19:24
-