Ifstream不会读取整数或其他任何东西

ifstream wont read integers, or anything else for that matter

本文关键字:其他 任何东 整数 读取 Ifstream      更新时间:2023-10-16

我使用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为雇员数,第二个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

当程序用来工作时输出是正确的

你的代码很好,为我工作

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

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

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

(TextWrangler在OSX上可能是一个很好的选择)

相关文章: