简体   繁体   English

C ++读取字符串int,从文本文件浮动到数组/字符串

[英]C++ reading strings,int,floats from a text file into a array/string

My .txt file contains the following 我的.txt文件包含以下内容

12345
John Smith
45 12.50
54234
Joe Paul
32 10.25
12324
Chris Lee
43 22.50

The first int is the employee ID, then the string name, then hours and rate of pay(float). 第一个int是雇员ID,然后是字符串名称,然后是小时和工资率(浮动)。

My Program: 我的计划:

using namespace std;

const int Size = 10;

typedef int intarray[Size];
typedef float farray[Size];
typedef string starray[Size];

void  readdata(intarray,starray,intarray,farray, ifstream &);
void  print(intarray,starray,intarray,farray,ifstream &);

int main()
{
    ifstream fin("data.txt");
    //ofstream fout;

    starray EmployeeName;
    intarray EmployeeID,EmployeeHoursWorked;
farray EmployeeRate;

readdata(EmployeeID,EmployeeName,EmployeeHoursWorked,EmployeeRate,fin);
print(EmployeeID,EmployeeName,EmployeeHoursWorked,EmployeeRate,fin);
cin.get();
cin.ignore();
}

My functions, my code is not properly reading the file. 我的功能,我的代码没有正确读取文件。

void readdata(intarray ID, starray Name, intarray Hours, farray Rate,    ifstream & infile)
{
for(int i = 0; i < Size; i++)
  {
//this code is not working as intended
   infile >> ID[i];
   getline(infile, Name[i]);
   infile >> Hours[i] >> Rate[i];

   infile.ignore();
 }     
} 

Im not getting any results. 我没有得到任何结果。

void print(intarray ID, starray Name, intarray Hours, farray Rate, ifstream & infile)
{
for(int i = 0; i < Size; i++)
  {
   cout << ID[i] << endl;
   cout<<Name[i]<<endl;
   cout << Hours[i] << Rate[i] << endl;


  }     
}   

When you call getline in readdata you are reading the end of line character after the ID. 当您在readdata中调用getline时,您正在读取ID之后的行尾字符。 You need to be positioned on the line with the name prior to calling getline. 在调用getline之前,您需要使用名称定位在该行上。 Try this 尝试这个

infile >> ID[i];
infile.ignore(); //Consume the new line char
getline(infile, Name[i]);
infile >> Hours[i] >> Rate[i];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM