簡體   English   中英

從.txt文件讀取的輸入輸出C ++

[英]input output C++ reading from a .txt file

我如何將其打印到輸出文件中,並按周以及按4周的總周數計算這些人的薪金總和和平均值...

范例txt檔案..

doe       jane
williams  tom
lons      adams

 45.7   56.3   345.6  344.7  // week 1
 43.6   89.0   543.6  12.5   // week 1  person 2
 90.5   78.0  345.4  345.6  //week 1 person 3
 67.5   34.5   56.6   34.5   // week2 person 1
  etc....for 4 weeks..

我知道使用循環有一種更簡單的方法,我可以得到一些幫助嗎,謝謝:)

這就是我到目前為止

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
using namespace std;

int main()
{
ifstream infile;
 ofstream outfile;

double s1, s2, s3 , s4 ,s5;
double t1, t2,t3,t4,t5;
double w1, w2,w3,w4,w5;
string personlast,personfirst,personlast2,personfirst2,personlast3,personfirst3;
double sum, average;
int numberpeople, numberofweeks;

infile.open("data.txt");
outfile.open("output.txt");

outfile<< fixed<< showpoint;
outfile<< setprecision(2);

infile>> numberpeople >> personlast >> personfirst >> personlast2 >> personfirst2>>
  personlast3 >> personfirst3 >> numberofweeks;
outfile<< " The number of salespeople are " << numberpeople <<"they are" <<
personlast << personfirst << "and " <<
 personlast2 << personfirst2 <<
 "and " << personlast3 << personfirst3 <<"Number of weeks = " << numberofweeks;


infile>> s1 >> s2 >> s3 >> s4 >> s5;
outfile <<" sales for week 1  "<< " for" << personlast << personfirst << s1 << s2
<< s3 << s4 << s5 << endl;
sum= s1+s2+s3+s4+s5;
 outfile <<"Sum of first week is " << sum<<endl;

infile >> t1 >> t2 >> t3 >> t4 >> t5;
outfile <<" sales for week 1  "<< " for" << personlast2 << personfirst2 << t1 << t2 
<< t3 << t4 << t5 <<endl;



infile.close();
outfile.close();
return 0;

我不想為您做家庭作業,因為我不想這么做,但我會給您一些入門的知識。 基本概念是遍歷文件,讀取每一行。 使用類似(偽代碼)的控件;

 while (string = readline() != EOF)
 {
     //split string on delimiters in this case spaces
     if (string piece is not an int)
     {
         // this is a name
         // set first and last name here
     }

     if (string piece is an int)
     {
        // set ints,
     }
 }

您還將需要一些結構(如果您已經了解了這些結構,則可能應該是類)來保存數據。 如果可以使用字符串,請使用它們代替那些char*如果使用char* ,則必須動態聲明一個char數組。 這樣,或者您可以將它們char[64] first_name; 如果允許的話。

struct person {
   char *first_name;
   char *last_name;
   numbers[4] numbers;
};

struct numbers {
   float item1;
   float item2;
   float item3;
   float item4;
};

讀取數據時,您需要將其讀取到人員結構的實例中。

暫無
暫無

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

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