为什么我程序开头的cout语句没有输出任何内容?

时间:2014-08-04 21:21:51

标签: c++

所以我正在研究一些类的代码。是的我知道我尝试解决的输入验证效率低下且程序未完成。我不需要其余的工作。这是代码。

/*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";

据我所知,这一行之前没有什么可以阻止程序输出&#34;一切都在开始&#34;但是&#34;一切都在开始&#34;永远不会出现在输出中。 代码构建并开始运行但从不停止并且无法输出任何内容。我的老师也无法解决这个问题。

我正在运行OSX10.9并将XCode用于我的编译器。我已经尝试过其他具有相同结果的编译器。

谢谢!

4 个答案:

答案 0 :(得分:4)

在这些循环中:

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

如果提取失败,PayrollFile开始转换为falseSubscript不再有任何增加的方法。所以外循环永远不会终止。

改为使用:

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

对于printf调试需求,在使用cout时,也请使用std::flushstd::endl。否则输出将被缓冲,并不能帮助您了解程序卡住的位置。 (对于实际写出大量数据,你要避免超过必要的冲洗,因为它会导致性能下降。)

答案 1 :(得分:1)

使用断点。当你开始调试时检查它们是否仍然是红色或变为白色。如果变成白色,你可以看到有关情况的说明。如果它的红色和你无法达到它意味着它永远不会到达那里。

答案 2 :(得分:0)

cout 缓冲流;强制输出你应该

  • 使用 endl 操纵器;
  • usinf flush()方法

答案 3 :(得分:0)

int ListOfPayrollCodes [NumOfCodes-1]; - //这行不应该编译。你使用变量来声明数组的大小。这应该是一个常数。

我不确定你是如何编译这段代码的。请修一个常数,看看它听起来如何。我硬编码并评论了Numcodes增量线,我可以打印出来。

更新:好的,看起来你在说编译器没有到达这一行。这意味着,代码无法编译。原因如上。

据我所知,您需要一个大小为ListOfPayrollCodes的数组。使用动态分配而不是静态分配,它将正常工作。