读取数据

时间:2015-07-05 08:59:57

标签: getline

这些问题无论如何都不能帮助任何人。

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题。请注意,如果您实际尝试在任何地方部署此类攻击,则会发生各种混乱。此代码非常不安全,因为它不会检查打开文件的失败程度,文件格式,或者正在读取的内容的大小,或者真正的....任何内容。

#include <stdio.h>
#include <iostream>

struct salesman
{
    char firstname[64];
    char lastname[64];
    char middleinitial[1];
    int averagecents;
    int totalcents;
};

int main ()
{
const char* inputFilename = "in.txt";
    int numberPeople = 0, weeksToHandlePerPerson = 0;
    int workweeklength = 5;
    int totalcents = 0;
    FILE * fileHandle = fopen ( inputFilename, "r" );
    fscanf ( fileHandle, "%d", &numberPeople );
    fscanf ( fileHandle, "%d", &weeksToHandlePerPerson );
    for ( int i = 0; i < numberPeople; ++i )
    {
        salesman nextsalesman;
        fscanf ( fileHandle, "%s", nextsalesman.firstname );
        fscanf ( fileHandle, "%s", nextsalesman.middleinitial ); 
        fscanf ( fileHandle, "%s", nextsalesman.lastname );

        float t1, t2, t3, t4, t5;
        fscanf ( fileHandle, "%f %f %f %f %f", &t1, &t2, &t3, &t4, &t5 );
        nextsalesman.totalcents = 100 * ( t1 + t2 + t3 + t4 + t5 );
        nextsalesman.averagecents = nextsalesman.totalcents / workweeklength;
        totalcents += nextsalesman.totalcents;
    std::cout << "salesman " << i << "total: $" << nextsalesman.totalcents / 100 << "." <<     nextsalesman.totalcents % 100
        << " and average $" << nextsalesman.averagecents / 100 << "." << nextsalesman.    averagecents % 100 << std::endl;
    }
    int averagecents = totalcents / ( numberPeople * weeksToHandlePerPerson );
std::cout << "total for all: " << totalcents / 100 << "." << totalcents % 100 << " and     average for all $" <<
        averagecents / 100 << "." << averagecents % 100 << std::endl;
    return 0;
}