C++ cin char 逐个符号读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7679246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ cin char read symbol-by-symbol
提问by tucnak
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?
我需要逐个符号阅读。但我不知道如何阅读,直到输入结束。例如,测试系统将 cin>>somecharvariable m 次。我必须逐个符号阅读所有字符。只有m次。我该怎么做?
采纳答案by Kerrek SB
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
.
在任何一种情况下,infile
都应该是类型std::istream &
或类似的,例如文件或std::cin
.
回答by Konrad Rudolph
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:
如果您只需要读取m
字符,请考虑使用for
循环:
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.
只要满足两个条件,就会运行循环:(1)m
已读取的字符数少于,以及 (2) 仍有要读取的字符。
However, both solutions have a drawback: they are relatively inefficient. It's more efficient to read the m
characters in one go.
然而,这两种解决方案都有一个缺点:它们的效率相对较低。一口气读完m
字符效率更高。
So first allocate a big enough buffer to store m
chars and then attempt to read them:
所以首先分配一个足够大的缓冲区来存储m
字符,然后尝试读取它们:
std::vector<char> buffer(m);
cin.read(&m[0], m);
unsigned total_read = cin.gcount();
Notice the last line – this will tell you whether m
characters have been actually read.
注意最后一行——这将告诉您m
字符是否已被实际读取。
回答by Sergey
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;
}