c++ - 如何在 C++ 中读取由要读取的字符数定义的文件段?

标签 c++ ifstream

我在从文件中读取特定数据时遇到一些问题。该文件的第一行和第二行有 80 个字符,第三行有未知数量的字符。以下是我的代码:

int main(){
    ifstream myfile;
    char strings[80];
    myfile.open("test.txt");
    /*reads first line of file into strings*/
    cout << "Name: " << strings << endl;
    /*reads second line of file into strings*/
    cout << "Address: " << strings << endl;
    /*reads third line of file into strings*/
    cout << "Handphone: " << strings << endl;
}

如何执行评论中的操作?

最佳答案

char strings[80] 只能容纳 79 个字符。将其设为char strings[81]。如果您使用 std::string,您可以完全忘记大小。

您可以使用 std::getline 读取行功能。

#include <string>

std::string strings;

/*reads first line of file into strings*/
std::getline( myfile, strings );

/*reads second line of file into strings*/
std::getline( myfile, strings );

/*reads third line of file into strings*/
std::getline( myfile, strings );

上面的代码忽略了第一行和第二行的长度为 80 个字符的信息(我假设您正在阅读基于行的文件格式)。如果重要的话,您可以添加额外的检查。

关于c++ - 如何在 C++ 中读取由要读取的字符数定义的文件段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13953240/

相关文章:

c++ - 指向 std::vector 元素的指针

c++ - 将 C++11 代码编译为 MATLAB mex 文件的一部分

c++ - 读取 anchors.fill 定义的 QML 元素大小 : parent

c++ - put 和 read 字符不匹配

C++ 在内存中加载二进制文件并获取对象

c++ - 在单元测试中,如何在不使用运算符== 的情况下比较两个对象,这可能会错过新成员?

c++ - 作用域枚举的 "using namespace X"等效项?

c++ - 在类中使用 ifstream

c++ - 使用 std::filebuf 时检测底层文件的完整性丢失?

c++ - 如果您只是重新创建 ifstream 类,您如何重载运算符>>?