문제

I have to make a program for a class that displays one star for every three degrees for each temperature read from an input file. I think I did ok, the code compiles. However, when I actually run it, I have a few problems:

1) when I run it without pressing ctrl+f5 in codelite it exits immediately, even though I have 'return 0;' at the end.

2) the console only shows stars for maybe half of the numbers, the rest are blank.

3) the numbers aren't lining up although I have set them all to the same width in my loop.

Here's what I see when I use ctrl+f5: http://imgur.com/w6jqPp5

Here's my code:

#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main() {

//declare variables for input/loops
string graphLine = " | ";
int tempCount = 0;
int tempStars;
int tempValue;
int printedStars;

//Title
cout << "Welcome to the Hourly Temperature Bar-Graph Maker 1.0!" << endl;

//read input file, name it "tempData"
ifstream tempData;
tempData.open("temperatures.txt");

//display error if the input file read failed
if(!tempData) { 
    cout << "ERROR: The input file could not be read." << endl;
    return 0;
    }

cout << "Temperatures for 24 hours(each asterisk represents 3 degrees): " << endl;  
//print the temperature range(horizontal label for graph)
cout << "-30        0       30      60      90      120" << endl;

//read a temperature, output the bar for each temperature
while (tempCount < 24) {

    //read in temperature value
    tempData >> tempValue;

        //distinguish between negative and positive temperatures
        if(tempValue >= 0) {
            tempStars = tempValue/3;
            cout << tempValue << setw(5) << graphLine;

            //print the appropriate number of asterisks for the temperature
            while (printedStars < tempStars) {
                cout << '*';
                printedStars++;
            }
            cout << endl;
        }

        //print the stars before the line
        else {
            tempStars = tempValue/3;

            while (printedStars < tempStars) {
                cout << '*';
                printedStars++;
            }
            cout << tempValue << setw(5) << graphLine << endl;
        }

    tempCount++;

}

tempData.close();
return 0;

}

도움이 되었습니까?

해결책

The program is just finishing normally - put a call to cin.getline or some other input call if you want it to wait. Alternatively run it through the debugger and put a breakpoint on the return 0 line.

You don't initialize or reset printedStars before you use it. Put printedStars = 0; before your star printing loops.

Move the setw(5) bit in the cout calls to before the value, so the value is output with a width of 5.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top