2014-04-04 49 views
0

這是我的CS1337類,所以我需要在主函數內工作。我不能使用任何東西,除了循環,if/else和switch語句。使用文件爲學生排隊 - 課堂作業

我在記事本中創建了一個Lines.txt文件,該文件應該有一個需要讀取的名稱列表。最終結果應該是讀取所有名稱並在控制檯輸出中顯示一條消息。

我根據我的代碼關閉前一個條目我在網上找到的位置: Question about my design for my C++ homework

任何幫助將不勝感激。

Lines.txt

Leslie 
Ron 
Tom 
Gerry 
Donna 
Andy 
April 
Chris 
Ben 
Mark 

控制檯窗口輸出:

Andy should be at the head of the line. 
Tom should be at the end of the line. 

我的代碼:

int main() 
{ 
    ifstream inputFile; 
    string filename; 

    string front, back, student; 
    int students = 10; 

    // Get the filename from the user. 
    cout << "Enter the filename: "; 
    cin >> filename; 

    // Open the file. 
    inputFile.open(filename.c_str()); 

    // If the file successfully opened, process it. 
    if (inputFile) 
    { 
/* A formula the sets each name entered to 
the variables front and back*/ 

    front = back = student; 

    // Read the numbers from the file and 
    // display them. 

    while (inputFile >> student) 
    { 
    for (int count = 1; count <= students; ++count) 
    { 
     // Create an if/else statement that decides which 
     // student name is alphabetically first and last 

    if (student < front) 
     front = student; 
    else if (student >= back) 
     back = student; 
    } 
    // Display the message showing which name is alphabetically first and last name 
    } 
    cout << endl 
     << front << " should be at the head of the line." << endl 
      << back << " should be at the end of the line." << endl; 
    // Close the file. 
    inputFile.close(); 
} 
    else 
{ 
    // Display an error message. 
    cout << "Error opening the file.\n"; 
} 
return 0; 
} 
+0

這個問題似乎是題外話,因爲它屬於上codereview.stackexchange.com – AShelly

+0

AShelly是正確的 - 你應該明確地說,這是行不通的,什麼輸出你得到這麼有人們的具體問題回答,否則這退化爲代碼審查。 –

回答

1

不是一個糟糕的開局。主要的問題是這樣的:

if (student < front) 

第一次遇到這種運行,front是一個空字符串...什麼都比較小於空字符串。也許最簡單的解決方法是:

if (count == 1) 
    front = back = student; 
else if (student < front) 
    ...etc... 

小挑剔:

  • 你的第一個front = back = student;什麼也不做......所有的字符串是缺省構造是空的反正。

  • 嘗試創建和初始化的變量越晚越好,例如... if (std::ifstream inputFile(filename) { ... } else { ...couldn't open... } - 無需.close()召喚爲std::ifstream將從其析構函數關閉文件。在C++ 11之前,您只需要.c_str()

+0

好吧,我得知我需要爲前面的字符串初始化一個值,以便它可以將自身與後面的字符串進行比較。問題是,如果我將if/else語句輸入到循環中。我現在將控制檯窗口輸出「Mark」作爲正面和背面。我嘗試輸入方程front = back = student;在循環開始之前,但在while循環內,我仍然得到相同的輸出。 – user3496053

+0

馬克是你輸入的最後一行,這表明你現在即使在計數!= 1時也設置front = back = student。檢查你是否按照我的回答放入了「if」條件,如果你仍然不能發現問題將您當前的代碼編輯到您的問題中,以便我可以看到您的意見。乾杯 –

+0

我明白了。原來,我需要它不斷地接受名稱的輸入來比較它。 inputFile >> student;這需要放在for循環中 – user3496053