问题
I have a little problem. I've created a program that asks user to enter part's name and part's price for four diffrent parts. Each name and price fills a structure, and I have an array of four structures. When i do a for loop to fill all the names and prices, my getline functon doesn't work properly, it simply just skipps the entering part after I enter the first part's name. Can you please tell me why? Here's my code:
#include <iostream>
#include <string>
struct part {
std::string name;
double cost;
};
int main() {
const int size = 4;
part apart[size];
for (int i = 0; i < size; i++) {
std::cout << "Enter the name of part № " << i + 1 << ": ";
getline(std::cin,apart[i].name);
std::cout << "Enter the price of '" << apart[i].name << "': ";
std::cin >> apart[i].cost;
}
}
回答1:
std::getline
consumes the newline character \n
, whereas std::cin
will consume the number you enter and stop.
To illustrate why this is a problem, consider the following input for the first two 'parts':
item 1\n
53.25\n
item 2\n
64.23\n
First, you call std::getline
, which consumes the text: item 1\n
. Then you call std::cin >> ...
, which recognises the 53.25
, parses it, consumes it, and stops. You then have:
\n
item 2\n
64.23\n
You then call std::getline
for a second time. All it sees is a \n
, which is recognised as the end of a line. Therefore, it sees a blank string, stores nothing in your std::string
, consumes the \n
, and stops.
To solve this, you need to make sure the newline is consumed when you store the floating-point value using std::cin >>
.
Try this:
#include <iostream>
#include <string>
// required for std::numeric_limits
#include <limits>
struct part {
std::string name;
double cost;
};
int main() {
const int size = 4;
part apart[size];
for (int i = 0; i < size; i++) {
std::cout << "Enter the name of part № " << i + 1 << ": ";
getline(std::cin,apart[i].name);
std::cout << "Enter the price of '" << apart[i].name << "': ";
std::cin >> apart[i].cost;
// flushes all newline characters
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
来源:https://stackoverflow.com/questions/35104540/why-wont-getline-function-work-multiple-times-in-a-for-loop-with-an-array-of-st