首页 > 解决方案 > 如何在 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;
}

提前致谢

标签: c++arraysstring

解决方案


它只读取一行数据的原因是因为这就是你告诉它要做的所有事情。这里:

...
 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


推荐阅读