0

Please someone clarify the issue I am having right now with user input in C++ [VS 2015].
I have a simple class StudentEntry

const int MAX_STUDENT = 50;
int entryCount = -1;

class StudentEntry {
public:
    StudentEntry(const std::string &s, std::vector<int> li) :   name(s), marks(li) {}
private:
    std::string         name;                                       
    std::vector<int>    marks; 
} 
* entryList[MAX_STUDENT];

Two non-member functions ask user to input name [string] and marks [vector<int>]:

std::string getName() {
    std::string input;
    std::cout << "Enter student name: ";
    std::cin >> input;
    return input;
}
std::vector<int> getMarks() {
    std::string line;
    int number;
    std::vector<int> input;

    std::cout << "Enter student marks separated by spaces: ";
    getline(std::cin, line);
    std::istringstream ss(line);
    while (ss >> number) {
        input.push_back(number);
    }
    return input;
}

My goal is to add a new entry using a function like addRecord(). What I plan to do, is:

int main() 
{
std::string in_name = getName();
std::vector<int> in_marks = getMarks();
entryList[entryCount] = new StudentEntry(in_name, in_marks);
...
}

However, I can't read a vector from user input. Basically, if I comment the line

std::string in_name = getName();

I can enter some marks and get them saved into in_marks. But after I read the in_name, the in_marks vector is not being read from the prompt.
Why is this happening?

user2376997
  • 501
  • 6
  • 22
  • 1
    Possible duplicate of [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – eesiraed Mar 27 '18 at 03:23
  • That's my thinking, @FeiXiang . I just can't explain why it would work the first time. – user4581301 Mar 27 '18 at 03:24
  • user2376997, Can we trouble you for a fuller picture in the form of a [mcve]? – user4581301 Mar 27 '18 at 03:25
  • @user4581301 There is no previous formatted extraction if `getName()` is not called. – eesiraed Mar 27 '18 at 03:25
  • 1
    What student name do you enter? If a full name with a space, then `std::cin >> input` reads only a first name, `while (ss >> number)` exits on attempt to read a second name as a number. – 273K Mar 27 '18 at 03:26
  • You've nailed it, @FeiXiang . I mis-read the question. – user4581301 Mar 27 '18 at 03:27
  • I simply type "Sam" for the name. And further type "98 99 87". Those numbers, however are not saved – user2376997 Mar 27 '18 at 03:32
  • 2
    In such case `getline(std::cin, line)` returns empty line and @FeiXiang already gave you the answer. – 273K Mar 27 '18 at 03:42
  • GOT IT! Thanks, @Fei Xiang, for the link with explanations. `std::cin.ignore()` can help. – user2376997 Mar 27 '18 at 03:42

0 Answers0