接受与结构数组相关的输入

Accepting input in relation to an array of structures

本文关键字:输入 数组 结构      更新时间:2023-10-16

我目前正在练习C++,我正在从教科书C++Primer Plus中做这个问题,我被困在最后一步。基本上,我要用一个包含汽车信息的结构制作一个数组,我遇到的问题是记录用户的输入。

我的代码:

#include <iostream>
#include <string>
struct car{
    std::string make;
    int year;
};
int main()
{
    std::cout << "How many cars do you wish to catalog? ";
    int lim;
    std::cin >> lim;
    car* info = new car[lim];
    for(int i = 0; i<lim; i++)
    {
        std::cout << "Please enter the make: ";
        getline(std::cin, info[i].make); // problem here..
        std::cout << "Please enter the year made: ";
        std::cin >> info[i].year; // problem here as well :(
    }
    std::cout << "here is your collection:n";
    while(int i = 0 < lim)
    {
        std::cout << info[i].make << " " << info[i].year << std::endl;
        //std::cout << "here is your collection:n"
        i++;
    }
    return 0;
}

有人可以帮助解释为什么它不起作用吗?

具体来说,我的问题是它没有正确获取我的输入,我的exe文件似乎跳过了"make"问题的输入并跳转到年份。然后它撞上了遗忘..可能是分段错误。

使用

std::cin >> lim;

    std::cin >> info[i].year;

换行符保留在流中,getline将其作为有效输入拾取。

您需要添加代码以忽略该行的其余部分。

std::cin >> lim;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n')

    std::cin >> info[i].year;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n')

请参阅有关 istream::ignore 的文档。

另外,更改

while(int i = 0 < lim)
{
    std::cout << info[i].make << " " << info[i].year << std::endl;
    //std::cout << "here is your collection:n"
    i++;
}

for(int i = 0; i < lim; ++i)
{
    std::cout << info[i].make << " " << info[i].year << std::endl;
    //std::cout << "here is your collection:n"
}
#include <iostream>
#include <string>
struct car{
    std::string make;
    int year = 0;
};
int main()
{
    int i = 0; //increment value
    std::cout << "How many cars do you wish to catalog? ";
    int lim;
    std::cin >> lim;
    car* info = new car[lim];
    for(i;  i < lim; i++)
    {
        std::cout << "Please enter the make: ";
        std::cin >> info[i].make; // change to cin, just like the one for year
        std::cout << "Please enter the year made: ";
        std::cin >> info[i].year; // this was fine
    }
    std::cout << "here is your collection:n";
    i = 0; //resets the increment value
    while(i < lim)
    {
        std::cout << info[i].make << " " << info[i].year << std::endl;
        //std::cout << "here is your collection:n"
        i++;
    }
    return 0;
}

将 CIN 和 getline 结合起来是......时髦。CIN 永远不会从第一个字符串中读取换行符,因此您的第一个 getline 调用几乎只会返回一个空白字符串。当我遇到这样的问题时,我通常会做的是在我的 cin 之后执行一次性 getline(( 调用。

结合Getline和CIN通常不是很友好。也许您应该切换到所有 getlines 并进行一些字符串操作?