为什么getline函数在带有结构数组的for循环中不能多次工作? [英] Why won't getline function work multiple times in a for loop with an array of structures?
问题描述
我有一个小问题.我创建了一个程序,要求用户输入四个不同零件的零件名称和零件价格.每个名称和价格都填充一个结构,我有四个结构的数组.当我执行for循环以填充所有名称和价格时,我的getline功能无法正常工作,在输入第一部分的名称后,它只是跳过输入的部分.你能告诉我为什么吗? 这是我的代码:
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;
}
}
推荐答案
std::getline
使用换行符\n
,而std::cin
将使用您输入并停止的数字.
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
首先,您调用std::getline
,它使用文本:item 1\n
.然后调用std::cin >> ...
,它识别53.25
,对其进行解析,使用它并停止.然后,您将拥有:
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
然后您再次拨打std::getline
.它所看到的只是一个\n
,它被认为是一行的结尾.因此,它看到一个空字符串,什么都没有存储在std::string
中,消耗了\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.
要解决此问题,您需要确保在使用std::cin >>
存储浮点值时使用换行符.
To solve this, you need to make sure the newline is consumed when you store the floating-point value using std::cin >>
.
尝试一下:
#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');
}
}
这篇关于为什么getline函数在带有结构数组的for循环中不能多次工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!