Help me please! do while / if else, with char isn't working.

hey you people, let me know where is the fault.

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
//opdracht_4.15_7
#include<iostream>
using namespace std;
int main()
{
	char ch, s;
	int telm = 0, telv = 0;
	
	cout << "voor man toets m in, voor vrouw toets v. druk dan op enter" << endl;
	
	do
{
	cin >> ch;
	cin.get();
		
	if (ch == 'm')	
	{
		telm = telm + 1;
	}
	
	else if (ch == 'v')
	{
		telv = telv + 1;	
	}
	
	else if (ch == 's')
	{
		ch = s;
	}
	
	else
	{
		cout << "nogmaals, voer m of v in." <<endl;
	}
}
	
	while (ch = s);
	
	cout << "aantal mannen is " << telm << " aantal vrouwen is" << telv << endl;
	return 0;
	}
let me know where is the fault.


If you let us know what the problem is.
It should loop as long as the user insert 'm' or 'v', not 's'. This condition is wrong:
while (ch = s);

Hints:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//opdracht_4.15_7
#include<iostream>

using namespace std; // <--- dangerous! Dangerous! Dangerous!

int main()
{
    char ch = '\0', s = '\0';
    int telm = 0, telv = 0;
    do {
        cout << "voor man toets m in, voor vrouw toets v *and s for exit*. "
                "druk dan op enter: ";
        cin >> ch;
        
        if      (ch == 'm') { telm = telm + 1; }
        else if (ch == 'v') { telv = telv + 1; }
        else if (ch == 's') { ch = s; }
        else                { cout << "nogmaals, voer m of v in.\n"; }
    } while (ch != s);
    
    cout << "aantal mannen is " << telm << "; aantal vrouwen is " << telv << '\n';
    return 0;
}

Wow Enoizat! you're a really professional!
Thank you so much, i have a good weekend now :)).

One question.. why is the: 'using namespace std; dangerous?
It violates encapsulation rules. Functions defined in different namespaces can only be called by their scope operator (i.e. std::shuffle). Using namespace std assumes that the default is std:: for all functions. This can lead to ambiguity in some cases and in others you will be calling a function you do no intend to. A brief example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <algorithm>
using namespace std;

void shuffle(std::vector<int>& numbers)
{
   //create custom function for sorting a vector of integers
}

int main()
{
    vector<int> test = {1,2,3,4,5};
    //which shuffle is being called?
    //Local shuffle or std::shuffle?
    shuffle(test);
     return 0;
}


It is always better to use specific scope than to assume use of a namespace.
Last edited on
why is the: 'using namespace std; dangerous?

knowclue’s answer is more than complete, but if you haven’t visited this site yet, it’s worth a visit:
https://isocpp.org/wiki/faq/coding-standards#using-namespace-std
Topic archived. No new replies allowed.