I am exploring some of the possibilities with the string template class defined in the <string> header. I wrote a small and simple program that registers names and associated ages. Throughout the program I use the getline() function template defined in the <string> header to read any input. The problem arises when I also try to use the normal cin object:
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::string;
using std::getline;
void ListNames(string names[], string ages[], size_t count)
{
cout << "\nThe names you entered are:\n";
for(size_t i = 0; i < count && !names[i].empty(); i++)
cout << names[i] << " aged " << ages[i] << ".\n";
return;
}
int main(void)
{
size_t count = 0;
cout << "How many names would you like to enter?\n";
// cin >> count;
cout << "\n";
string* pnames = new string [count];
string* pages = new string [count];
string firstname;
string secondname;
for(size_t i = 0; i < count; i++)
{
cout << "Enter a first name or press enter to end:\n";
getline(cin, firstname, '\n');
if(firstname.empty())
{
ListNames(pnames, pages, i);
cout << "Done!\n";
return 0;
}
cout << "Enter a second name:\n";
getline(cin, secondname, '\n');
*(pnames + i) = firstname + ' ' + secondname;
cout << "Enter " << *(pnames + i) << "'s age:\n";
getline(cin, *(pages + i), '\n');
}
cout << "No space for more names.\n";
ListNames(pnames, pages, count);
cout << "\n";
delete [] pnames;
delete [] pages;
return 0;
}
As soon as I uncomment cin >> count; the program 'falls through' the getline(cin, firstname, '\n'); at line 33. The result is an end to the program after an empty list of names is written to the console screen. Could someone please explain to me why this is happening?
Update: I found out that cin does not clear the newline character from the string, which explains the behavior of my program. With the use of cin.ignore() everything works as it should. But could someone elaborate on this a bit more?
A statement like this cin >> count; when executed will ignore any leading whitespace (including space, tab or newline) if there happens to be any, before the integer which was entered by the user. Then it reads from the input just the characters it needs to satisfy the request for an integer. As soon as it encounters any character which is not a valid part of the integer, it stops getting input, and leaves the remaining characters, whatever they may be, in the input buffer.
Im a beginner aswell, so dont bash me if this doesnt work. But i was tought that you cannot give variables a name that is a C++ keyword. And im pretty sure "count" is a C++ keyword.
Instead of
"size_t count"
try this :
"size_t nCount"