如何从我的结构中打印人口最多的状态
How can I print the most populous state from my structure?
我需要打印用户输入的3个人口最多的状态。我需要通过使用结构并比较用户也输入的三个状态的种群来做到这一点。它不运行,但也不会有任何错误。编译器刚才。
struct state_struct {
string name;
int pop;
};
int main()
{
state_struct state[3];
int i;
string mystr, print_most_pop;
for (i = 0; i < 3; i++)
{
cout << "Enter name of state:" << endl;
getline(cin, state[i].name);
cout << "Enter population for state:" << endl;
getline(cin, mystr);
stringstream(mystr) >> state[i].pop;
}
for (i = 0; i < 3; i++)
{
if (state[i].pop > state[i + 1].pop && state[i].pop >state[i+2].pop)
print_most_pop = state[i].name;
if (state[i].pop > state[i + 1].pop && state[i].pop < state[i +
2].pop)
print_most_pop = state[i + 2].name;
if (state[i].pop < state[i + 1].pop && state[i].pop > state[i +
2].pop)
print_most_pop = state[i + 1].name;
}
cout << "The most populous state you entered is " << print_most_pop <<
endl;
return 0;
}
您只需要一个循环,只需跟踪您输入的最大人口即可。您也无需进行任何复杂的计算即可确定最大值,仅如果n.pop> current_max,然后将您的current_max设置为n。您还可以将int pop
直接从cin
放入结构中,而无需将其从字符串转换为stringstream。您可以循环直到输入实际上是可以确保的整数类型。
#include <iostream>
#include <limits>
using namespace std;
struct state_struct {
string name;
int pop;
};
int main()
{
state_struct state[3];
state_struct biggest {"none", 0};
for(int i = 0; i < 3; i++)
{
cout << "Enter name of state:" << endl;
getline(cin, state[i].name);
cout << "Enter popuation for state:" << endl;
// make sure population is an integer type
while(!(cin >> state[i].pop))
{
cout << "Invalid value! Please enter a number." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
if (state[i].pop > biggest.pop)
{
biggest = state[i];
}
}
cout << "The most populous state is " << biggest.name << " with " << biggest.pop << endl;
return 0;
}
相关文章:
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- OSX MetalKit CVMetalTextureCacheCreateTextureFromImage失败,状态:
- std::future_error:无关联状态
- 如何避免LED在循环状态变化中闪烁?
- boost 是否有按特殊类型值编码状态"compact optional"?
- 为什么系统函数总是在C++中返回已转移的退出状态?
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 当可输入框在窗口中处于活动状态时获得通知的任何方法
- 检查两个节点在子节点上是否具有相同状态的更优雅的方法
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- C++部分概念 id:显式模板规范顺序/第一个参数的特殊状态的原因是什么?
- 试图在崇高中奔跑. 错误 已发生: 收集2.exe: 错误: ld 返回 1 退出状态
- 在容器上移动分配:以前包含的对象的状态
- collect2:错误:ld 返回 1 个退出状态未定义的引用
- 具有动态大小的特征矩阵的默认初始状态
- 如何从Clojure调用C++程序,以使程序保持打开状态?
- 如何从我的结构中打印人口最多的状态