簡體   English   中英

如何將文本文件輸入轉換為 c++ 中的數組

[英]How do i convert a text file input to an array in 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超出該范圍,那么您將獲得未定義的行為。

假設您的數據文件中的數據不超過 200,否則您的程序將失敗。

您只從文件中讀取一次,因此只獲取第一行數據。 您需要從文件變紅直到 EOF。 在 if(infile.is_open()){} 中添加一個 while 循環。 閱讀直到 EOF,如下所示。

if (infile.is_open())
        {
            while (infile >> mobilenumber[i] >> seatnumber[i] >> firstname[i] >> lastname[i]) {
                cout << "Reading file" << endl;
                i++;
                numberofbooking++;
            }
        }

除了索引之外,我沒有看到 i++ 的任何好處。 我認為您也可以使用numberofbooking進行索引。

每當您遇到此類問題時,請嘗試添加日志以檢查正在發生的事情或使用調試器。 希望這會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM