Why isn't this working?

1
2
3
4
5
6
7
8
9
10
11
12
void bookType::setAuthor(int authorCount)
{
    string name;
    cout << "Enter the name of the author and then press enter." << endl;
    
    for(int i = 0; i < authorCount; i++)
    {
        getline(cin, name);
        author[i] = name;
        numOfAuthor++;
    }
}


This is the code that I have so far. This method receives the number of authors that a book has as a parameter, asks the user for the name of the authors, keeps track of the number of authors for the class bookType, and then assigns the names to the array author that is a private attribute of the class bookType.

Let's say that the author count is two. For some reason, the first element in the array author is skipped and the getline method is skipped also. It allows me to enter a name on the second iteration of the loop though, and stores the name into the element 1 of author (author[1].) Does anyone know what I am doing wrong, or why the first iteration of getline and element 0 is skipped?
Probably because you have an extra '\n' left over in the buffer from previous input. For example:

1
2
int x;
std::cin>>x; //this leaves an extra '\n' in the buffer  
I've got everything commented out in my code except for the necessary statements to carry out this method, and the problem still occurs. This is the only input that I am getting from the user at the moment. Maybe I'm just not understanding your solution.
Hi

There seems to be lots of code missing here, so I can't really comment in much detail.

What I have done however is to modify the script to do exactly what you claim it does (save author and update count), perhaps you can look at my code and modify accordingly.

I personally can't see anything wrong in the snippet of code you're displaying here - where exactly is your array defined? Do you perform any operations on it previously?


I'm also curious - why are you passing in the variable for authorCount - you don't appear to be doing anything with it.

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
#include <iostream>
#include <string>

using namespace std;

#define authorCount 10
string author[authorCount];
int numOfAuthor;

//void setAuthor(int authorCount)
void setAuthor()
{
    string name;
    cout << "Enter the name of the author and then press enter." << endl;

    for(int i = 0; i < authorCount; i++)
    {
        getline(cin, name);
        author[i] = name;
        numOfAuthor++;
    }

}

int main()
{
  setAuthor();
  for (int i = 0; i < authorCount; i++) {
    cout << author[i] << " " << i <<  endl;
  }

return 0;
}
Last edited on
Topic archived. No new replies allowed.