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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:20:37  来源:igfitidea点击:

C++ cin char read symbol-by-symbol

c++streamcharcin

提问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, infileshould 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 mcharacters, consider using a forloop:

如果您只需要读取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 mcharacters 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 mcharacters in one go.

然而,这两种解决方案都有一个缺点:它们的效率相对较低。一口气读完m字符效率更高。

So first allocate a big enough buffer to store mchars 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 mcharacters 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;
}