c++ - 如何从文件读取特定数量的字符到结构
问题描述
我需要从这个数据文件中读取 20 个字符:
7
Petras A. Petraitis 120 15 20 0
Jurgis Jurgutis 222 16 12 22
Rimas Jonas 138 15 15 59
Bei Lin Sin Mun 23 15 0 0
Zigmas Nosis 256 16 23 9
Romas Senasis 111 15 15 15
Jurgis Stasys Lydeka199 16 13 9
6
256 16 43 15
120 15 50 10
111 16 5 35
199 16 35 59
222 16 42 22
23 15 30 0
基本上每个字母和空格直到数字。我曾尝试使用 read(),但我无法让它与 struct 一起使用。我也一直在尝试使用 getline(),但它对我也不起作用。我一直在到处寻找,但大多数教程都显示直接用户输入,而不是从文件中读取。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct competition{
string name; // athletes name
int athleteNum; // number
int startHours; // starting time: hours
int startMin; // starting time: minutes
int startSec; // starting time: seconds
};
int main()
{
ifstream duom ("U2.txt");
competition athletes[30];
int n; // amount of athletes
duom >> n;
for (int i=0; i<n; i++){
duom.getline(athletes[i].name, 20);
}
return 0;
}
使用 getline() 代码无法编译,所以我可能语法错误并且 read() 似乎不适用于 struct。
解决方案
正如 alezh 指出的那样,istream::getline()
需要 a char*
not a std::string
。您可以创建一个char hold[50]
变量传递给istream::getline()
: duom.getline(hold, 50);
,然后将您的分配std::string
给那个 : athletes[i].name = std::string(hold, 20);
。
也正如他指出的那样,duom >> n;
不会让你进入下一行。您可能希望duom.ignore(20, '\n')
在该行之后从正确的行开始。或者首先不使用>>
with getline
。
嵌套for
循环有什么用?您可以摆脱第二for
行。
推荐阅读
- java - BigInteger#nextProbablePrime 是否至少精确到 64 位数字?
- c# - VSTO:在已发送项目中创建虚假电子邮件时出现问题
- android - 为什么我用 Firebase 中的数据填充的 Recyclerview 显示为空白?
- c - 将 REQ_NEXT_CHAR 限制为 ncurses 表单字段中的内容长度
- java - 我的应用程序完美地在模拟器上运行。但是当我将它安装在我的 android 设备上时它没有运行
- elasticsearch - Elasticsearch 客户端:加快客户端创建速度
- c - SWIG 在 perl 包中导致“符号查找问题”
- javascript - 将事件侦听器添加到 svg 的动态元素
- reactjs - 当父状态更新时,React 钩子会更新子状态
- c# - 使用 Steamworks.NET 包装器时未触发回调