Help with while loop

Pages: 12
do i need a header for numeric_limits<std::streamsize>::max()? because its giving me errors
#include <climits> If you want you can put a number there like 1024 or 80 or w.e that is just how many characters you will ignore. http://www.cplusplus.com/reference/climits/

you can also use #include <limits>
http://www.cplusplus.com/reference/limits/numeric_limits/?kw=numeric_limits
http://www.cplusplus.com/reference/limits/
Last edited on
@Ch1156
I don't believe there is anything wrong with the loop in the OP. Can you provide the rest of the code (posted to pastebin or similar if it is large)?
Well here is what i have right now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*
//Crypto Guess is based off of Crypto Logic for the Oddessy 2
//Created Tuesday, June 4th 2013 by Chay Hawk
*/

#include <iostream>
#include <string>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <time.h>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ifstream;
using std::ofstream;
using std::vector;
using std::fstream;

string word_list(string GL)
{
    string store_word;
    vector<string> words;
    srand(time(0));

    ifstream fileIn;
    fileIn.open(GL.c_str());

    if(fileIn.fail())
    {
        cout << "File failed to open." << endl;
    }

    while(!fileIn.eof())
    {
        /*not needed as vectors resize themselves
        if(words.size() == words.capacity())
        {
            words.reserve(words.size() * 3);
        }
        */
        fileIn >> store_word;
        words.push_back(store_word);
    }

    fileIn.close();

    return words[rand() % words.size()];
}

void save_game(int save_rightGuesses,
               int save_wrongGuesses,
               string save_list_type,
               time_t save_hours_playtime,
               time_t save_minutes_playtime,
               time_t save_seconds_playtime
              )
{
    time_t current = time(0);
    ofstream fileOut;
    fileOut.open("Scores.txt", fstream::app);

    fileOut << "CRYPTO GUESS SCORES FOR " << ctime(&current) << endl;

    fileOut << "From list: " << save_list_type << endl;
    fileOut << "Right Guesses: " << save_rightGuesses << endl;
    fileOut << "Wrong Guesses: " << save_wrongGuesses << "\n" << endl;

    fileOut << "Your Play Time is " << save_hours_playtime << " Hours " << save_minutes_playtime << " Minutes " << save_seconds_playtime << " Seconds\n" << endl;

    fileOut.close();
}

int main()
{
    srand(time(0));

    string original_word,
           shuffled_word,
           random_word,
           choose_list,
           guess,
           custom_word,
           copy_custom_word,
           guess_custom_word;

    int guess_number = 1,
        right_guesses = 0,
        wrong_guesses = 0,
        select = 0;

    bool game1_loop = true,
         game2_loop = true,
         choice_loop = true;

    cout << "CRYPTO GUESS" << endl;
    cout << "Version 2.3\n" << endl;

    cout << "Do you want to enter words yourself or have the computer give you words?" << endl;
    cout << "1) Enter words myself" << endl;
    cout << "2) Have the computer give me words" << endl;

    while(cout << "Please make a selection -> " &&
          cin >> select && (select<1 || select>2))
    {
        cin.clear();
        cin.ignore(50, '\n');
        cout << "That is not a valid selection." << endl;
    }

/*
    while(choice_loop)
    {
        cin >> select;

        switch(select)
        {
            case 1:
                break;
            case 2:
                break;
            default:
                cout << "Not a valid input" << endl;
        }
    }
*/
    cin.ignore(50, '\n');

    cout << '\n';

    if(select == 1)
    {
        while(game1_loop)
        {
            cout << "Enter your word" << endl;
            getline(cin, custom_word);

            copy_custom_word = custom_word;
            random_shuffle(custom_word.begin(), custom_word.end());

            cout << string(55, '\n');

            cout << "The word is " << custom_word << endl;
            cout << "Your guess is: ";
            cin >> guess_custom_word;

            if(guess_custom_word == copy_custom_word)
            {
                cout << "Thats correct!" << endl;
                guess_custom_word = " ";
                break;
            }
        }
    }

    if(select == 2)
    {
        time_t startTime = time(0);
        cout << "Select list" << endl;
        getline(cin, choose_list);

        while(game2_loop)
        {
            string HWLF = word_list(choose_list);
            shuffled_word = HWLF;
            random_shuffle(shuffled_word.begin(), shuffled_word.end());//#1

            cout << "----------------------------------------------------" << endl;
            cout << "|| Guess # " << guess_number << " || Right Guesses: " <<
                    right_guesses << " || Wrong Guesses: " << wrong_guesses << endl;
            cout << "----------------------------------------------------\n" << endl;

            cout << "Word: " << shuffled_word << endl;

            cout << '\n';

            while(guess != HWLF)
            {
                cout << "Your guess: ";
                cin >> guess;

                if(guess == HWLF)
                {
                    cout << "Is correct!\n" << endl;
                    guess = " ";
                    guess_number++;
                    right_guesses++;
                    break;
                }
                else if(guess == "Quit" || guess == "quit")
                {
                    cout << "Goodbye thanks for playing." << endl;

                    time_t endTime = time(0),
                           playTime = endTime - startTime,
                           hoursTime = playTime / 3600,
                           minutesTime = (playTime / 60) % 60,
                           secondsTime = playTime % 60;

                    save_game(right_guesses,
                              wrong_guesses,
                              choose_list,
                              hoursTime,
                              minutesTime,
                              secondsTime);

                    game2_loop = false;
                    return 0;
                }
                if(guess == "Skip" || guess == "skip")
                {
                    cout << "You skipped the word." << endl;
                    cout << "The correct word was " << HWLF << endl;
                    cout << '\n';
                    wrong_guesses++;
                    break;
                }
                else
                {
                    wrong_guesses++;
                    cout << "Is wrong! Try again\n" << endl;
                }
            }
        }//End of game while loop
    }//End of if statement
}
Last edited on
Im ripping out my hair trying to figure this out, what other people suggested isnt working, and everything i tried isnt working. I was so desperate i even resorted to using goto, which is something i NEVER EVER EVER use or want to use but i did, and even that didnt work. I was thinking about putting my whole code in a switch statement, i mean the game parts, i think that might solve the problem but idk. what do you all thingk.
Last edited on
Hi Chay,

It seems to me that you haven't actually tried what I suggested. I am starting to get the impression that no one has read the code in the link that I posted.

Try this snippet (Not tested):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// put this before main()
void ShowMenu;

// put all this in main()
bool Quit = false;
int MenuSelection = 0;

while (!Quit) {
     ShowMenu();

     cin >> MenuSelection;

     switch(MenuSelection) {
          case 1 :

               //call function to do this menu item
               break;
     
          case 2 :
               //call function to do this menu item
               break;
     
          case 3 :
               Quit = true;
               std::cout << "Quitting program\n";
               return 0; // omit this line if you execution to continue after while loop
               break;
     
          default :
                std::cout << "Bad Input - options are 1 or 2 or 3\n";
     }

}

// put this after main()
void ShowMenu() {
    std::cout << "CRYPTO GUESS" << std::endl;
    std::cout << "Version 2.3\n" << std::endl;

    std::cout << "Do you want to enter words yourself or have the computer give you words?" << std::endl;
    std::cout << "1) Enter words myself" << std::endl;
    std::cout << "2) Have the computer give me words" << std::endl;
    std::cout << "3) Quit" << std::endl;
}


I hope this is clear now. 8+)
> Im ripping out my hair trying to figure this out, what other people suggested isnt working,
> and everything i tried isnt working.

Get out of the habit of writing a monstrous main; factor the code into small functions, and you would find it a lot easier.

To get you started on that path:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <iostream>
#include <string>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <fstream>

// read a random string from the file
std::string random_word( const std::string& path_to_file )
{
    std::ifstream file( path_to_file.c_str() ) ;
    std::string selected ;

    int num_words = 0 ;
    std::string word ;
    while( file >> word )
    {
        ++num_words ;
        if( std::rand() % num_words == 0 ) selected = word ;
    }

    return selected ;
}

inline std::string time_stamp( std::time_t t = std::time(0) )
{ return std::asctime( std::localtime(&t) ) ; }

void save_game( int right_guesses, int wrong_guesses,
                const std::string& list_file_name,
                std::time_t start_time, std::time_t end_time = std::time(0) )
{
    std::ofstream fout( "Scores.txt", std::ios::app ) ;
    fout << "CRYPTO GUESS SCORES FOR " << time_stamp() << '\n'
         << "From list: " << list_file_name << '\n'
         << "Right Guesses: " << right_guesses << '\n'
         << "Wrong Guesses: " << wrong_guesses << "\n\n" ;

    int seconds = ( std::difftime( end_time, start_time ) ) ;
    fout << "Your Play Time is " << seconds/3600 << " Hours "
         << (seconds/60)%60 << " Minutes " << seconds%60 << " Seconds\n\n" ;

}

void menu()
{
    std::cout << "CRYPTO GUESS" << "Version 2.3\n\n"
           << "Do you want to enter words yourself or have the computer give you words?\n\n"
           << "1) Enter words myself\n"
           << "2) Have the computer give me words\n"
           << "3) Quit\n" ;
}

int get_selection( const std::string& prompt, int minv, int maxv )
{
    std::cout << prompt << ": " ;
    int selection ;
    if( std::cin >> selection && selection >= minv && selection <= maxv )
        return selection ;
    std::cin.clear() ;
    std::cin.ignore( 1024, '\n' ) ;
    std::cerr << "inavalid selection. please enter an integer in ["
               << minv << '-' << maxv << "]\n" ;
    return get_selection( prompt, minv, maxv ) ;
}

// the main game loop; return true to continue playing
bool play_game( int& right_guesses, int& wrong_guesses, std::string list_file_name )
{
    const std::string word = random_word(list_file_name) ;
    if( word.empty() )
    {
        std::cerr << "error reading word list file\n" ;
        return false ;
    }

    std::string shuffled_word = word ;
    std::random_shuffle( shuffled_word.begin(), shuffled_word.end() ) ;
    std::cout << shuffled_word << '\n' ;
    std::cin.ignore( 1024, '\n' ) ;

    std::string guess ;
    std::getline( std::cin, guess ) ;

    while( guess != "quit" )
    {
        // if( guess == word )
        // etc...

        // else if( guess == "skip" )
        // ...

        // else // wrong guess
        // ...

        return true ; // not quit, continue playing
    }

    return false ; // quit

    // TODO: **** if you find that this function is getting too big,
    // break it up further
}

int main()
{
    std::srand( std::time(0) ) ;
    menu() ;
    int select = get_selection( "Please make a selection", 1, 3 ) ;

    if( select == 1 )
    {
        // ...
    }

    else if( select == 2 )
    {
        std::time_t start_time = std::time(0) ;
        int right_guesses = 0 ;
        int wrong_guesses = 0 ;
        std::string list_file_name = "words.txt" ;
        std::cout << "file containing words? " ;
        std::cin >> list_file_name ;

        // call a function to execute the game loop to play the game
        // till play_game returns false
        while( play_game( right_guesses, wrong_guesses, list_file_name ) ) ;

        save_game( right_guesses, wrong_guesses, list_file_name, start_time ) ;
    }
}

Its not that my code is too big thats the problem, i can manage it just fine. My main is only 146 lines, ive written a main that was around 1500 lines and i managed it just fine so thats not an issue. what i was refering to was that i could not get my program to loop my select variable so if the player entered a wrong item it wouldnt quit. I already figured it out. There is nt anything wrong with the code i wrote.
Ch1156 wrote:
My main is only 146 lines, ive written a main that was around 1500 lines and i managed it just fine so thats not an issue.


It's a bad idea to have functions that are too long - there is a bit of an idea that functions shouldn't be longer than 80 lines, others go for even less 20 or 30 say.

It is all about good organisation, ease of reading & can help prevent errors. If you write psuedo code as comments before doing your actual code - it could help you decide what should go into a function.

JLBorges really knows his stuff, he didn't give you that advice just for laughs, so could take his advice on-board?

You wouldn't write a 1500 page book without chapters, nor would you write a 15 page chapter without paragraphs.

HTH
How do you guys learn stuff like that? like programming etiquette basically? is there a site where i can learn stuff like that? not actual code just rules and ideas on how you should program.
Well I for one didn't learn things like that from a webpage. Some other ways:

Get your code looked at by some one who who knows what they are doing. Like at University with assignments, or by the knowledgeable people on a forum. (Btw I am not claiming that I have a lot of knowledge - much, much more for me to learn)

If you go through the experience of writing code, having it constructively criticised, and taking that on board - then you have added to your knowledge base.

There are some really good books, - I have a Scott Meyers Effective C++, and Design Patterns Book by Gamma et al. But those are a bit more advanced. Some other obvious Authors might be Bjarne Stroustrop and Herb Sutter as 2 examples to start with.

Some of it is actual theory - like Object Oriented Design Principles for example.

The other thing might be coding standards. This is the Google one - there are others.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Inline_Functions


I guess the goal is to write organised, clear, elegant, efficient & simple code (as far as that goes).

Hope all goes well.
> is there a site where i can learn stuff like that?
> not actual code just rules and ideas on how you should program.

The best resource that I know of is a slim book: 'The Practice of Programming' by Kernighan and Pike.
http://www.amazon.com/Practice-Programming-Addison-Wesley-Professional-Computing/dp/020161586X
Topic archived. No new replies allowed.
Pages: 12