接受与结构数组相关的输入
Accepting input in relation to an array of structures
我目前正在练习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 并进行一些字符串操作?
相关文章:
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- C++逗号分隔的输入数组代码过早退出
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 cin 输入数组值
- 与 C++ 中一行中的用户输入数组元素相关的问题
- 将整数输入数组的方法比 scanf() 或 cin 更快?
- 如何在C 中动态输入数组
- 我想添加两个字符串类型的矩阵.用户将不会输入行数或列的数量.用户将仅输入数组
- 测试用户输入数组中的重复项的最有效方法是什么?
- 在用户输入数组中查找元音
- 如何将用户输入数组值移动到数组末尾并将其设置为 0
- 函数是否可以用较小的输入数组编写输入数组
- C++ 将数字输入数组并输出
- 需要帮助传递数组和输入数组
- 用户输入数组大小(N).从 0 到 N 的数字填充数组
- 输入int之后的字符的c++输入数组
- 合并排序 - 返回新数组,而不是将合并的数组复制到输入数组
- 在C 函数中声明输入数组的大小
- 在 cpp 中使用 getline 输入数组中的空格分隔数字