For Loop + Arrays problem

I got a problem about the program...

This is the sample output->
1
2
3
4
5
6
7
8
9
10
11
12
13
14
1. Cars: AA11 
Hours: 2

2. Cars: BB22 
Hours: 4

3. Cars: CC33 
Hours: 6

4. Cars: DD44 
Hours: 8

5. Cars: EE55 
Hours: 10



This is my coding->

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream.h>

void main ()
{
	char cname[5];
	int n, hour;

	for (n=1; n<=5; n++) {
		cout << n << ". Cars: ";
		cin.getline(cname, 5);
		cout << "Hours: ";
		cin  >> hour;
		cout << endl;
	}
}




This is my output->
1
2
3
4
5
6
7
8
9
1. Cars: AA11
Hours: 2

2. Cars: Hours: BB22

3. Cars: Hours:
4. Cars: Hours:
5. Cars: Hours:
Press any key to continue_



Can anyone tell me what's my mistake for my coding???
Thanks...^_^
Last edited on
1.Don't post more than 1 of the same thing
2. Make question more clear
Main problem is that you're using both getline() and cin>>. Mixing them up gives problems, I recommend you to always use getline(). See http://www.cplusplus.com/forum/articles/6046/
And you have to put an endline before "Hours:" and a second endline at the end of the for-loop to get the exact same output as the sample.
Most of the problem is that cin >> hour; leaves whitespace -- in this case the newline character, which is then read by the next iteration of cin.getline(cname, 5); as a completed line, since it sees the newline character as the end of input.

In order to get around this problem, you need to clear the newline character after cin >> hour. Normally, this is done with cin.get();

1
2
cin >> hour;
cin.get();


That will resolve some of the trouble you're having. There are other troubles with this program that this solution does not address, but as long as you input exactly what your program is expecting, you should be able to limp along.
Topic archived. No new replies allowed.