简体   繁体   English

C ++程序不会进入循环

[英]C++ program wont enter for loop

When I try to print the sorted data I can't get the program to enter the for loop. 当我尝试打印排序的数据时,我无法让程序进入for循环。 How do I fix this? 我该如何解决? This is the full code for those who wanted to see the rest of it. 对于那些想看其余内容的人来说,这是完整的代码。 The for loop that isn't working is the for loop in the main function. 不起作用的for循环是main函数中的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;
}

显然,“ cards”的大小仍为0。请使用cout << cards.size()进行确认。

Your temp_file_name string is not defined and nothing gets writen to disk. 您的temp_file_name字符串未定义,并且没有任何内容写入磁盘。 This leaves the cards vector empty. 这使得卡矢量为空。

Card_index is a signed integer, but cards.size gives you a size_type value, which is a unsigned integer. Card_index是一个有符号整数,但是cards.size为您提供一个size_type值,它是一个无符号整数。

If you are sure nothing wrong in for loop, this might be a problem. 如果确定在for循环中没有问题,则可能是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM