【问题标题】:C++ reading strings,int,floats from a text file into a array/stringC ++从文本文件中读取字符串、整数、浮点数到数组/字符串中
【发布时间】:2015-03-05 20:41:54
【问题描述】:

我的 .txt 文件包含以下内容

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

第一个 int 是员工 ID,然后是字符串名称,然后是小时数和工资率(浮点数)。

我的程序:

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();
}

我的函数,我的代码没有正确读取文件。

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();
 }     
} 

我没有得到任何结果。

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;


  }     
}   

【问题讨论】:

  • Re: P.S.: 你可以用赋值语句将数据填充到数组中以解决读取问题。
  • 一点点错误处理会大有帮助。尝试添加一些代码,例如if (infile.bad()) cout &lt;&lt; "can't read file";
  • 我很确定 print 不应该读取任何文件。
  • 是的,为什么你的print 函数附近有infile
  • 哦,是的。小错误。它仍然给我错误的输出。它正确读取第一行“12345”然后吐出垃圾/随机数

标签: c++ arrays string file-io


【解决方案1】:

当您在 readdata 中调用 getline 时,您正在读取 ID 之后的行尾字符。在调用 getline 之前,您需要定位在名称所在的行上。试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多