gpt4 book ai didi

c++ - ifstream 不会读取整数或其他任何与此相关的内容

转载 作者:行者123 更新时间:2023-11-30 05:40:55 28 4
gpt4 key购买 nike

我正在使用 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

其中第一个整数是员 worker 数,第二个整数是周数,每周为 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

当用于运行的程序输出正确时。

最佳答案

您的代码很好,适合我。

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

您可以使用 notepad++ 去除 BOM,如下所述:

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

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

关于c++ - ifstream 不会读取整数或其他任何与此相关的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31334764/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com