我在从文件中读取特定数据时遇到一些问题。该文件的第一行和第二行有 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/