簡體   English   中英

為什么程序開頭的cout語句不輸出任何內容?

[英]Why does a cout statement at the beginning of my program not output anything?

所以我正在為一個類編寫一些代碼。 是的,我知道我要計算的輸入驗證效率低下,並且程序尚未完成。 我不需要其余的工作。 這是代碼。

/*Write a program that allows the user to enter a payroll code.
 The program should search for the payroll code in the file and then display the appropriate salary.
 If the payroll code is not in the file, the program should display an appropriate message.
 Use a sentinel value to end the program.*/

#include <iostream>
#include <string>
#include <fstream>
using namespace std;


int main(){
    int code;
    ifstream PayrollFile;
    int FCode;
    int Salary;
    char Trash;
    string line;
    string lineTwo;
    int NumOfCodes=0;
    int Subscript=0;

    cout << "everything is starting";

    PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");

    do{
        lineTwo=line;
        PayrollFile >> line;
        NumOfCodes++;
    }
    while (line!=lineTwo);

    PayrollFile.close();
    PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");

    int ListOfPayrollCodes[NumOfCodes-1];

    while (Subscript<NumOfCodes){
        while (PayrollFile >> FCode >> Trash >> Salary) {
            cout << FCode;
            ListOfPayrollCodes[Subscript]=FCode;
            Subscript++;
        }
    }

    PayrollFile.close();
    PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");

    cout << "please enter the payroll code";
    cin >> code;

    while (PayrollFile >> FCode >> Trash >> Salary) {
        if (code==FCode) {
            cout << "The salary is " << Salary << endl;
        }
    }
    PayrollFile.close();
}

我感到困惑的是,編譯器似乎從未達到這一行:

cout << "everything is starting";

據我所知,在此行之前沒有什么可以阻止程序輸出“一切都在開始”,但“一切都在開始”永遠不會出現在輸出中。 該代碼會生成並開始運行,但永遠不會停止並且不會輸出任何內容。 我的老師也無法弄清楚。

我正在運行OSX10.9,並將XCode用於我的編譯器。 我試過其他具有相同結果的編譯器。

謝謝!

在這些循環中:

while (Subscript<NumOfCodes){
    while (PayrollFile >> FCode >> Trash >> Salary) {
        cout << FCode;
        ListOfPayrollCodes[Subscript]=FCode;
        Subscript++;
    }
}

如果提取失敗, PayrollFile開始轉換為false ,且不再有任何方式Subscript增加。 因此,外循環永遠不會終止。

而是使用:

while ((Subscript<NumOfCodes) && (PayrollFile >> FCode >> Trash >> Salary)) {
    cout << FCode;
    ListOfPayrollCodes[Subscript]=FCode;
    Subscript++;
}

為了滿足您的printf調試需求,在使用cout ,還請使用std::flushstd::endl 否則,輸出將被緩沖,並不能幫助您了解程序卡在哪里。 (對於實際寫出大量數據,您將希望避免不必要的刷新操作,因為這會降低性能。)

使用斷點。 當您開始調試時,請檢查它們是否仍然是紅色或變成白色。 如果變成白色,則可以看到有關情況的注釋。 如果它紅色,而您無法到達,則表示它永遠不會到達那里。

cout緩沖流 ; 強制輸出你應該

  • 使用endl機械手;
  • usinf flush()方法

int ListOfPayrollCodes [NumOfCodes-1]; -//此行不應編譯。您正在使用變量聲明數組的大小。 這應該是一個常數。

我不確定您如何編譯此代碼。 請修正一個常數,然后看看它的發音。 我對其進行了硬編碼,並注釋了Numcodes增量線,然后可以打印出來。

更新:好的,您似乎在說編譯器沒有達到這一行。 這意味着代碼不會編譯。 原因是上面的。

我了解您需要一個大小為ListOfPayrollCodes的數組。 使用動態分配而不是靜態分配,它將可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM