首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从.txt文件读取输入输出C++

问从.txt文件读取输入输出C++
EN

Stack Overflow用户
提问于 2012-11-17 09:02:08
回答 1查看 2.2K关注 0票数 0

我如何将其打印到输出文件,并计算这些人的工资总和和平均按周和按总周4周…

示例txt文件..

代码语言:javascript
复制
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..

我知道使用循环有一种更简单的方法,我能得到一些帮助吗谢谢:)

这是我到目前为止所拥有的

代码语言:javascript
复制
#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;
EN

回答 1

Stack Overflow用户

发布于 2012-11-17 09:26:43

我不会为你做作业,因为我不想做,但我会给你一些开始的东西。基本概念是循环遍历文件,读取每一行。使用像(伪代码)这样的控件;

代码语言:javascript
复制
 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[64] first_name;。

代码语言:javascript
复制
struct person {
   char *first_name;
   char *last_name;
   numbers[4] numbers;
};

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

当您读取数据时,需要将其读取到person结构的实例中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13426606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档