ifstream不会读取整数或其他任何内容

时间:2015-07-10 07:18:30

标签: c++ file-io

我正在使用xcode。我编译好,然后一旦运行它成功打开文件然后读取两个值,但值不进入变量,因此它跳过for循环并关闭文件并从main返回。

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

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

int main(int argc, const char * argv[]) {

    //setup variables
    const char* inputFilename = "TheSales.txt";
    int numberPeople = 0, weeksToHandlePerPerson = 0;
    int workweeklength = 5;
    int totalcents = 0;

    //open file

    std::ifstream fileHandle;
    fileHandle.open(inputFilename, std::ios::in | std::ios::app);
    if(!fileHandle)
        perror ( "Stream Failed to open because: " );


    fileHandle >> numberPeople;              <----- does not get value
    fileHandle >> weeksToHandlePerPerson;    <----- does not get value


    //do calculations
    for ( int i = 0; i < numberPeople; ++i )    <---- this gets skipped
    {
        Salesman nextsalesman;
        fileHandle >> nextsalesman.firstname;
        fileHandle >> nextsalesman.middleinitial;
        fileHandle >> nextsalesman.lastname;



        float t1, t2, t3, t4, t5;
        fileHandle >> t1 >> t2 >> t3 >> t4 >> t5;

        nextsalesman.totalcents = 100 * ( t1 + t2 + t3 + t4 + t5 );
        nextsalesman.averagecents = nextsalesman.totalcents / workweeklength;
        totalcents += nextsalesman.totalcents;

        //print calculations calculateNumbers()
        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;
    }
    fileHandle.close();  <---- this works
    return 0;            <---- then we return main.
}

文件:

3
2
firstName1 A lastName1
20.00 25.00 30.90 40.00 55.50
20.00 25.00 30.90 40.00 55.50
firstname2 B lastName2
30.00 24.00 45.00 67.00 65.50
56.90 87.00 43.50 56.98 55.40
firstName3 C lastName3
62.00 34.50 12.50 34.00 34.90
70.00 80.00 90.00 65.00 39.00

其中第一个int是员工人数,第二个是周数,每周是5天。

Actual output:   

Expected output:

(fake output but expected form)

salesman1 total: 23424 avg: 3654
salesman2 total: 234   avg: 1654
salesman3 total: 424   avg: 364.

total for all: 5345683  and average for all: 34564564

用于处理输出的程序是正确的。

1 个答案:

答案 0 :(得分:1)

您的代码很好,适合我。

您是否正在使用文本编辑器在TheSales.txt的开头写出一个unicode字节顺序标记?如果是这样,那么它会使你的程序混淆。

您可以使用记事本++来剥离BOM,如下所述:

http://www.larshaendler.com/2015/01/20/remove-bom-with-notepad/

(OSX上的TextWrangler可能是一个不错的选择)