为什么程序开头的cout语句没有输出任何东西?

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

本文关键字:输出 任何东 语句 程序 开头 cout 为什么      更新时间:2023-10-16

所以我正在为类编写一些代码。是的,我知道输入验证我试图工作是低效的,程序是未完成的。我不需要剩下的东西起作用。下面是代码。

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

据我所知,在这行之前没有任何东西应该阻止程序输出"everything is starting",但是"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++;
}

对于您的打印调试需要,当使用cout时,也使用std::flushstd::endl。否则输出将被缓冲,而不能帮助您了解程序在哪里卡住了。(对于实际写入大量数据,您将希望避免不必要的刷新,因为这会降低性能。)

使用断点。当您开始调试时,检查它们是否仍然是红色或变成白色。如果变成白色,你可以看到一个关于情况的说明。

cout缓冲流;要强制输出,您应该

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

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

我不知道你是如何编译这段代码的。请固定一个常数,看看它听起来如何。我对它进行了硬编码,并注释了Numcodes增量行,我可以打印它。

更新:好吧,看起来你是说编译器没有达到这一行。这意味着代码不能编译。原因如上。

我知道你想要一个大小为ListOfPayrollCodes的数组。使用动态分配而不是静态分配,它会工作得很好。