c++ - 如何在 C++ 中将文本文件输入转换为数组
问题描述
嗨,我有一个格式为 phonenumber housenumber firstname lastname 的文本文件
我正在尝试读取所有数据并将其存储在数组中。我已经使用了下面的代码。但它只读取第一行数据。谁能帮助我为什么会这样。
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string.h>
#define Size 200
unsigned long long int mobilenumber[Size];
char seatnumber[Size][4];
char firstname[Size][30],lastname[Size][30];
using namespace std;
int main()
{
//delcares the files needed for input and output//
ifstream infile;
ofstream outfile;
infile.open("reservations.txt",ios::in);
//opens files needed for output//
outfile.open("pricing.txt");
int i=0;
if (infile.is_open())
{
infile>> mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i];
i++;
numberofbooking++;
}
infile.close();
for(int i=0;i<=numberofbooking;i++)
{
cout<< mobilenumber[i]<<" "<< seatnumber[i]<<" "<< firstname[i]<<" "<< lastname[i];
}
return 0;
}
提前致谢
解决方案
它只读取一行数据的原因是因为这就是你告诉它要做的所有事情。这里:
...
if (infile.is_open())
{
infile>> mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i];
i++;
numberofbooking++;
}
...
这将运行一次,我认为你的意思是一个 while 循环:
while (infile>> mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i])
{
i++;
numberofbooking++;
}
只要超出该范围0 <= i <= 199
,这将做您想做的事,那么您将获得未定义的行为。i
推荐阅读
- python - Python 字符串/参数操作
- python - CircleCI 没有拾取运行步骤中定义的环境变量?
- c# - 用于动态调用的错误泛型重载
- php - 如何从 vshare.io 响应式获取嵌入代码?
- javascript - 使用箭头键 ExtJs 滚动页面的组合框
- c++ - 我如何创建一个使用该类创建的所有对象的链接列表?
- mysql - MySQL 函数在 SELECT 后使用 RETURN 变量进行 UPDATE
- html - data-os-animation : 动画进出?
- ruby-on-rails - Rails 5 中模型功能的装饰器模式
- python - Python - 爬虫