2014-03-28 61 views
0

我必須爲每個從輸入文件讀取的每個溫度每三度顯示一個星形的類進行編程。我認爲我沒有問題,代碼編譯。然而,當我真正運行它時,我遇到了一些問題:條形圖程序行爲奇怪

1)當我在代碼庫中不按Ctrl + F5運行它時,它立即退出,即使我'返回0;'最後。

2)控制檯只顯示大概一半數字的星星,其餘都是空白的。

3)雖然我已將它們全部設置爲我的循環中相同的寬度,但數字並不對齊。

這是我看到的時候我用ctrl + F5:http://imgur.com/w6jqPp5

這裏是我的代碼:

#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; 

}

+0

我認爲問題出在其他部分的寬度輸出,首先你有沒有初始化printedStars的價值。第二個if()條件是檢查tempValue> = 0;意味着它只會在tempValue爲負值時轉到其他部分,而在其他部分中,您正在檢查while(printedStars Himanshu

回答

0

該計劃剛剛完成正常 - 把一個呼叫cin.getline或者其他一些輸入呼叫,如果你想等待。或者通過調試器運行它,並在返回0行上放置一個斷點。

在使用它之前,您不要初始化或重置printedStars。在您的明星打印循環之前放入printedStars = 0;

將在COUT的setw(5)位調用前值,所以該值與5

+0

謝謝尋求幫助!我原以爲我需要重新設置印刷之星......但是我絕對不知道我需要把setw放在前面。我唯一沒有得到的是添加「cin.getline()」,我補充說,並得到一個錯誤。還嘗試添加一個斷點,但它仍然會在打開時關閉。 – yves

+0

嘗試'std :: getchar();'代替。這隻會等待來自控制檯的字符輸入。 –