C++ 如何将文本文件输入转换为c++;
嗨,我有一个文本文件的格式 电话号码房屋号码名字姓氏 我试图读取所有数据并将其存储在一个数组中。我使用了下面的代码。但它只读取第一行数据。谁能帮我解释一下为什么会发生这种事C++ 如何将文本文件输入转换为c++;,c++,arrays,string,C++,Arrays,String,嗨,我有一个文本文件的格式 电话号码房屋号码名字姓氏 我试图读取所有数据并将其存储在一个数组中。我使用了下面的代码。但它只读取第一行数据。谁能帮我解释一下为什么会发生这种事 #include <iostream> #include <iomanip> #include <fstream> #include <string.h> #define Size 200 unsigned long long int mobilenumber[Size];
#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;
}
#包括
#包括
#包括
#包括
#定义大小200
无符号长整型mobilenumber[Size];
字符seatnumber[大小][4];
字符firstname[Size][30],lastname[Size][30];
使用名称空间std;
int main()
{
//Delcare负责输入和输出所需的文件//
河流充填;
出流孔的直径;
open(“reservations.txt”,ios::in);
//打开输出所需的文件//
outfile.open(“pricing.txt”);
int i=0;
if(infle.is_open())
{
infle>>mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i];
i++;
numberofbooking++;
}
infle.close();
对于(int i=0;i,它只读取一行数据的原因是因为这就是您告诉它要做的所有事情。这里:
。。。
if(infle.is_open())
{
infle>>mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i];
i++;
numberofbooking++;
}
...
这将运行一次,我想你的意思是一个while循环:
while(infle>>mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i])
{
i++;
numberofbooking++;
}
这将满足您的需要,只要假设数据文件中的数据不超过200,否则您的程序将失败
您只从文件中读取一次,因此只获取第一行数据。
您需要从文件开始直到EOF。在if(infle.is_open()){}.Read-till-EOF中添加一个while循环,如下所示
if (infile.is_open())
{
while (infile >> mobilenumber[i] >> seatnumber[i] >> firstname[i] >> lastname[i]) {
cout << "Reading file" << endl;
i++;
numberofbooking++;
}
}
if(infle.is_open())
{
而(infle>>mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i]){
你是否需要一个循环来读取比第一行更多的内容。而不是infle>>mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i];
你想要while(infle>>mobilenumber[i]>>seatnumber[i]>>firstname[i]){i++;numberofbooking++;}
谢谢,这样做了:)我没有发布答案,因为这是一种非常常见的问题。我希望有一个重复的。@drescherjm有意义。根据建议编辑。