如何从我的结构中打印人口最多的状态

How can I print the most populous state from my structure?

本文关键字:人口 状态 打印 我的 结构      更新时间:2023-10-16

我需要打印用户输入的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;
}