Loops

ok I have fixed all my other problems now need Help to get my loop/ if stmt to work right.

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
// InvalidBinDr.cpp 

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

// FILL IN InvalidBin PROTOTYPE: 

 
int main()
{
	// Variables local to main
	bool inValid=true;	// True if an invalid binary # is entered
	string input;// The user entered string

while (true) {
    cout << "Enter a binary number (8 digits or less): ";
    getline(cin, input);
    if (input.size() <= 8) break;
    cerr << "You entered more than 8 digits.  Please re-enter your number." << endl;
}



	if(inValid)
		cout << input << " is not a binary number." << endl;
	else
		cout << input << " is a binary number." << endl;



	return 0;
}

// FUNCTION InvalidBin RETURNS TRUE IF THE STRING ENTERED BY THE
// USER DOES NOT REPRESENT A VALID 8-BIT BINARY NUMBER OTHERWISE
// IT RETURNS FALSE, (i.e. the string has 8 bits that are 1's or 
// 0's only).



So if anyone can help me with this issue please post.
I believe this should fix your problem:

(Just ignore some of my formatting preferences. :-P)

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
 
// InvalidBinDr.cpp

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

// FILL IN InvalidBin PROTOTYPE:


int main()
{
	// Variables local to main
	bool inValid=true;	// True if an invalid binary # is entered
	string input;// The user entered string

    while (true)
    {
        cout << "Enter a binary number (8 digits or less): ";
        getline(cin, input);
        if (input.size() <= 8)
        {
            inValid = false;
            break;
        }
        else
            cerr << "You entered more than 8 digits.  Please re-enter your number." << endl;
    }

    if( !inValid )
        cout << input << " is a binary number." << endl;
    else
        cout << input << " is not a binary number." << endl;

	return 0;
}
 

The problem was that inValid was true when the string is not valid but was never set to false when it is true.
Well, read lines 8 and 36-39 of the original code. The assignment is to write the InvalidBin function and then call it from main() at the correct location.
Topic archived. No new replies allowed.