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

标签 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;
    }
}

最佳答案

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');
    }
}

关于c++ - 为什么 getline 函数不能在具有结构数组的 for 循环中多次工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35104540/

相关文章:

java - 在没有 OpenCv 包管理器的情况下在 Eclipse 上创建 Android OpenCV 项目

c - 程序无法运行(编译问题)

c++ - boost program_options : Read in 3d Vector as Command Line Parameter

arrays - 如何用C实现埃拉托色尼筛法算法?

javascript - 即使我使用 React.js 映射包含 1,000 个对象的数组,如何一次仅将 25 个对象渲染到屏幕上

c++ - 新手编码器在这里 : C++ Copying vector into array using functions

java - 从 indexof(word) 到下一行的子字符串

Java 正则表达式字符串#replaceAll 替代

c++ - 为什么Qt图表示例不删除动态分配的变量

c++ - Eigen中的内存是如何布局的?