ernie
ernie

Reputation: 37

How come the first letter in my final cout gets cut off?

int main () {
    const int MAX_INPUT = 99;
    string names[MAX_INPUT];
    string eraseName;
    string newList;
    int numNames = 0;
    int i = 0;


    cout << "How many names do you want (max 99)? ";
    cin >> numNames;   

    do {
        if(numNames > MAX_INPUT) {
            cout << "Out of memory!" << endl;
            break;
        }  
        cout << "Enter name #" << (i+1) << ": ";
        cin.ignore();
        getline(cin,names[i]);
        ++i;
    }  
    while (i < numNames);

    cout << "What name do you want to eliminate? ";
    getline(cin,eraseName);
    cout << "Here is the list in reverse order, skipping ";
    cout << eraseName << "..." << endl;

    i = 0;
    for (i = 0; i < numNames; ++i) {
        cout << names[i] << endl;
    }       
    return 0;
} 

I have an assignment where I have to "eliminate" an element in an array and recreate the output. I know my final for loop will not erase the element, it's just there because I was testing the issue, but if names has two inputs (John Doe and Jane Doe) and I say to cout them the final loop couts:

John Doe
ane Doe

Upvotes: 3

Views: 1635

Answers (2)

R Sahu
R Sahu

Reputation: 206697

The following block of code

if(numNames > MAX_INPUT) {
   cout << "Out of memory!" << endl;
   break;
 }  

does not need to be executed in every iteration of the do-while loop. You can change you function to use:

if(numNames > MAX_INPUT) {
   cout << "Out of memory!" << endl;
   // Deal with the problem. Exit??
}

do {
    cout << "Enter name #" << (i+1) << ": ";
    cin.ignore();
    getline(cin,names[i]);
    ++i;
}  while (i < numNames);

Once you move the check out of the loop, you have to ask yourself, "Do I need to ignore a character in each iteration of the loop?" The answer is "No". You need to ignore the newline only after reading numNames. So, you move it out of the loop also.

if(numNames > MAX_INPUT) {
   cout << "Out of memory!" << endl;
   // Deal with the problem. Exit??
}

// Ignore the newline left on the stream before reading names.
cin.ignore();

do {
    cout << "Enter name #" << (i+1) << ": ";
    getline(cin,names[i]);
    ++i;
}  while (i < numNames);

You can improve on that by making sure that everything up to and including the newline is ignored by using:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Add

#include <limits>

to be able to use std::numeric_limits.

Upvotes: 1

Barmar
Barmar

Reputation: 781848

Move cin.ignore() right after cin >> numNames;, before the loop that reads the names.

You only need this to ignore the newline that is left in the stream after reading the number of names. getline() reads (and ignores) the newline from the stream, so there's no need to call ignore() again before reading each name. As a result, it's reading and ignoring the first character of the name.

Upvotes: 3

Related Questions