Arrays

Hello i'm confused why this code does not work properly. The first for loop skips the first execution, when I enter how many names I want, it starts from name 2 instead of 1 weird I just cant seem to get it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  int howmany = 0;
	std::cout << "how many names?  ";
	std::cin >> howmany;
	std::string *names = new std::string[howmany];
	std::cout << "\n\n";
	for (int x = 0; x < howmany; x++)
	{
		std::cout << "Enter name " << x + 1 << ":  ";
		std::getline(std::cin, names[x]);
	}
	std::cout << "\n\n";
	for (int x = 0; x < howmany; x++)
	{
		std::cout << "Name " << x + 1 << ":  " << names[x] << "\n";
	}
	system("PAUSE");
	return 0;
Its becuase you first use cin >> to get the howmany, then you switch to "getline".

What you want to do is, put a cin.ignore(); after the cin >>.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        int howmany = 0;
	std::cout << "how many names?  ";
	std::cin >> howmany;
	cin.ignore();
	std::string *names = new std::string[howmany];
	std::cout << "\n\n";

	for (int x = 0; x < howmany; x++)
	{
		
		std::cout << "Enter name " << x + 1 << ":  ";
		std::getline(std::cin, names[x]); 
	}
	std::cout << "\n\n";
	for (int x = 0; x < howmany; x++)
	{
		std::cout << "Name " << x + 1 << ":  " << names[x] << "\n";
	}
Last edited on
The program asks `how many names?'. You type your name and press enter so the following input will be sent to the program "sourcedesigns\n". Note that extra newline character \n at the end. It is inserted when you press enter.

std::cin >> howmany; will read the next word, "sourcedesigns" leaving "\n" still in the input buffer.

std::getline reads until it finds a newline character and because a newline character was left over from previous input it will return right away giving an empty string.

If you enter the first name on the same line as the howmany count it should work.

3Bob
Rob
Flob

This is of course not what you want. What you should do is that you remove the newline character after using the >> operator. There are a few different ways.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Removes the next character. Works great if there is no 
// extra input between the number and the newline character.
std::cin.ignore();

// Removes the rest of the line, including the newline character
// but will not work for lines more than 100 characters.
std::cin.ignore(100, '\n');

// Same as above but will work for any line length that the program can handle.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

// Removes all whitespace characters up until the first non-whitespace character.
// Will in most cases have the same result as above but if the next line starts with
// a spaces they will be removed too. 
std::cin >> std::ws;
Last edited on
Thanks guys
Topic archived. No new replies allowed.