我正在使用xcode。我編譯得很好,然後一旦運行它成功打開文件,然後讀取兩個值,但值不會進入變量,因此它會跳過for循環並關閉文件並從main返回。ifstream不會讀整數,或其他任何事
#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
當程序用於工作的輸出是正確的。
什麼是 「TheSales.txt」 的內容是什麼? –
與你的問題和你的問題無關,但爲什麼使用固定大小的數組作爲字符串?爲什麼不[[std :: string']](http://en.cppreference.com/w/cpp/string/basic_string)? –
爲什麼你打開文件閱讀和使用應用程序標誌? – Mackiavelli