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

2024-01-11

我有一个小问题。我创建了一个程序,要求用户输入四个不同零件的零件名称和零件价格。每个名称和价格都填充一个结构,我有一个由四个结构组成的数组。当我执行 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;
    }
}

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

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

item 1\n
53.25\n
item 2\n
64.23\n

首先,你打电话std::getline,它消耗文本:item 1\n。然后你打电话std::cin >> ...,它认识到53.25,解析它,消耗它,然后停止。然后你有:

\n
item 2\n
64.23\n

然后你打电话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');
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 getline 函数不能在具有结构数组的 for 循环中多次工作? [复制] 的相关文章

随机推荐