为什么 getline 函数不能在具有结构数组的 for 循环中多次工作?

lil*_*ick 3 c++ arrays string for-loop getline

我有一个小问题。我创建了一个程序,要求用户输入四个不同零件的零件名称和零件价格。每个名称和价格都填充一个结构,我有一个包含四个结构的数组。当我执行 for 循环来填充所有名称和价格时,我的 getline 函数无法正常工作,它只是在我输入第一部分的名称后跳过输入部分。你能告诉我为什么吗?这是我的代码:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Arc*_*des 5

std::getline消耗换行符\n,而std::cin将消耗您输入和停止的数字。

为了说明为什么这是一个问题,请考虑前两个“部分”的以下输入:

item 1\n
53.25\n
item 2\n
64.23\n
Run Code Online (Sandbox Code Playgroud)

首先,您调用std::getline,它使用文本:item 1\n。然后调用std::cin >> ...,它识别53.25、解析它、使用它并停止。然后你有:

\n
item 2\n
64.23\n
Run Code Online (Sandbox Code Playgroud)

然后你std::getline第二次打电话。它看到的只是一个\n,它被认为是一行的结尾。因此,它看到一个空白字符串,在您的 中不存储任何内容std::string,消耗\n,然后停止。

要解决此问题,您需要确保在使用 存储浮点值时使用换行符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');
    }
}
Run Code Online (Sandbox Code Playgroud)