2015-10-28 300 views
0

當我嘗試打印排序後的數據時,我無法讓程序進入for循環。我該如何解決?這是希望看到其餘部分的完整代碼。不工作的for循環是主函數中的for循環。C++程序不會輸入for循環

#include<string> //provieds strings 
#include<iostream> //providescin and cout 
#include<algorithm> //provides sort() 
#include<vector> // provides vector 
#include<fstream> // provides file input and output 

using namespace std; 
string temp_file_name; 
const int NUMBER_OF_RANKS = 13; 
const int NUMBER_OF_SUITS = 4; 
string ranks[NUMBER_OF_RANKS] = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; 
string suits[NUMBER_OF_SUITS] = { "Hearts", "Diamonds", "Spades", "Clubs" }; 


void GenerateTestData() 
{ 
    ofstream output_file; 
    output_file.open(temp_file_name); 
    for (int suit_index = 0; suit_index < NUMBER_OF_SUITS; suit_index++) 
    { 
     for (int rank_index = 0; rank_index < NUMBER_OF_RANKS; rank_index++) 
     { 
      output_file << ranks[rank_index] << "of" << suits[suit_index] << endl; 
     } 
    } 
    output_file.close(); 
} 

vector<string> ReadTestDataBackIn() 
{ 
    ifstream input_file; 
    vector<string> cards; 
    string buffer; 
    input_file.open(temp_file_name); 
    while (getline(input_file, buffer)) 

    { 

     cards.push_back(buffer); 

    } 
    input_file.close(); 
    return cards; 
} 

int main() 
{ 
    vector<string> cards; 

    GenerateTestData(); 
    cards = ReadTestDataBackIn(); 

    sort(cards.begin(), cards.end()); 
    //This loop 
    for (int card_index = 0; card_index < cards.size(); card_index++) 
    { 
     cout << cards[card_index] << endl; 
    } 

    system("pause"); 
    return 0; 
} 
+2

ReadTestDataBackIn()在做什麼?給你完整的代碼。 – Mukit09

+0

for循環沒有錯......必須是其他功能 – wrangler

+2

你確定'cards'有元素嗎?嘗試'if(cards.empty())cout <<「facepalm」<< endl;'。 – Beta

回答

1

您的temp_file_name字符串未定義,也沒有任何內容寫入磁盤。這將卡片矢量留空。

+0

謝謝,這就是我現在需要修復它的工作正常。 – user5496267

1

顯然, 「卡」 仍然是大小爲0 確認與 COUT < < cards.size()

0

Card_index是有符號整數,但cards.size給你一個SIZE_TYPE值,是一個無符號整數。

如果你確定for循環沒有問題,這可能是一個問題。

+0

這隻會是一個問題,一旦循環已完成INT_MAX'迭代次數 –