【问题标题】:How to read a specific amount of characters如何读取特定数量的字符
【发布时间】:2020-10-05 04:39:10
【问题描述】:

我可以使用以下代码从控制台获取字符: 每次换行显示 2 个字符

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main()
{
    char ch[3] = "";

    ifstream file("example.txt");

    while (file.read(ch, sizeof(ch)-1))
    {
       cout << ch << endl;
    }

    return 0;
}

我的问题是,如果字符集是奇数,它不会显示文本文件中的最后一个字符!

我的文本文件包含以下内容: abcdefg

它不会在控制台中显示字母 g 它显示这个:

  • ab
  • 光盘
  • ef

我想这样显示:

  • ab
  • 光盘
  • ef
  • g

我想用它一次读取一个大文件的 1000 个字符,所以我不想逐个字符地读取,这需要很多时间,但如果你能修复它或有更好的建议,分享给我

【问题讨论】:

    标签: c++ c++11 c++17


    【解决方案1】:

    以下代码应该可以工作:

    while (file) {
        file.read(ch, sizeof(ch) - 1);
        int number_read_chars = file.gcount();
        // print chars here ...
    }
    

    通过将read 调用移动到循环中,您将能够处理最后一个调用,其中可用字符太少。 gcount 方法将为您提供上次未格式化输入操作实际读取了多少字符的信息,例如read.

    请注意,当读取少于sizeof(ch) 字符时,如果您打算将缓冲区用作C 字符串,则必须在gcount 返回的位置手动插入NUL 字符,因为这些字符为空终止:

    ch[file.gcount()] = '\0';
    

    【讨论】:

    • 读取少于 2 个字符时不要忘记空终止。
    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2013-06-03
    • 1970-01-01
    • 2015-02-04
    • 2018-10-26
    相关资源
    最近更新 更多