I don't understand why it does this...

Hi thanks for reading. I am learning some of the basics and I wrote a really simple program to practice them.

One of my functions behaves differently depending on where in main() it gets called from. I do not understand why it will work correctly called from one spot, but behave incorrectly when called from another.

When the function is working correctly, it will prompt the user to enter a name, then ask a second time. Both names are then displayed. The function works correctly called at the beginning of main().

When the function is called from inside the switch statement, it displays both prompts but the first one is skipped and the input not recorded. Only the second name is acknowledged and recorded.

The program looks fine to me, I do not see why the function wouldn't work correctly. But it doesn't work right.

I appreciate your help and insight. It seems like a very normal thing to try and do, it freaks me out that it does not work how I think it should.

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
using namespace std;
#include <iostream>
#include <ctype.h>

int menu(void);
void charexample(void);


int main()
{
	//charexample(); // when called here it runs fine
	
	int select = 0;
	int quit = 0;

	do
	{
		select = menu();
		
		switch(select)
		{
			case 0:
			default:
				quit = 1;
			break;
			case 1:
				charexample(); // when called here it behaves WRONG. Why?
			break;
		}
		cout << endl;

	}while(quit != 1);

	return(0);
}


// FUNCTIONS

int menu(void)
{
	int option = 0;
	cout << "MENU" << endl << endl;
	cout << "\t1. Char Example" << endl;
	cout << "\t0. Quit" << endl;
	cout << "> ";
	cin >> option;

	return option;
}

void charexample(void)
{
	char name[2][20];

	for(int n=0; n<2; n++)
	{
		cout << "Enter Name #" << (n+1) << ": ";
		cin.getline(name[n],20);
		cout << endl;
	}

	for(int i=0; i<2; i++)
	{
		cout << "Name #" << (i+1) << ": " << name[i] << endl;
	}
}
Last edited on
You probably have a carrige return stuck in your input buffer. Try calling "std::cin.sync()" after you user input. http://www.cplusplus.com/reference/istream/basic_istream/sync/
You must be right, adding sync solved it. Thank you. Appreciate the linkage too, I took a look but gonna look again and really grasp. Such a relief to know what the cause is.
Topic archived. No new replies allowed.