简体   繁体   中英

c++ User input validation in sorted array

Hello i have a assinment that im making a weater program where we ask the user to enter info

first enter how many citys to use

then enter city name and degrees

then i will print out the list in order starting with the coldest city

and last i need to add a search funkar to search by degrees to find a location with that degrees

this one i havent started with

but my MAIN problem is that i need to validate that the user input is between -60 and 60 when enter the city and degrees... i just dont get it to work with anything... can someone please help out?`

cout<<"Enter Name of City and degrees \n\n";

for(i=0;i<n;i++){
    cout<<"---------\n";
    cin>>s_array[i].name;
    cin>>s_array[i].degrees;

this is the code where user put in city and degree EX Rio 50

i just dont know how to validate it to be between -60 and 60`

First of all, you should create a class. I understand from your code you must use class. If you don't have to it is easier than this. Then you should create an object.

Basic logic below here. You should create a class well.

 class Weather //create class
 
 Weather city // create object
 
 
 
 cout<<"Please enter a city name:"<<endl;
 
 cin>>city.name;
 
 cout<<"Please enter a city degree:"<<endl;
 
 cin>>city.degrees;

What you're looking for, is simple data validation.

Assuming you have a struct City:

// used to hold the data
struct City {
     string name;
     double degrees;
};

and in your main() , you have initialised an array of these structs:

bool temperatureValid(const City);

int main() {
    const int32_t totalCities = 12;
    City cities[totalCities];
    for (int32_t i = 0; i < totalCities; i++) {
        // add data to structs
        cout << "Enter city name: ";
        cin >> cities[i].name; // you might want to validate this, too
        cout << "Enter temperature: ";
        cin >> cities[i].degrees;
        cout << cities[i].name << " has a temperature of " << cities[i].degrees << "°" << endl;

        if (temperatureValid(cities[i])) {
            // cool... or not
        } else {
            cerr << "Invalid temperature range!" << endl;
            --i; // make sure we can do this one again
            continue;
        }
    }
    return 0;
}

bool temperatureValid(const City city) {
    return city.degrees >= -60 && city.degrees <= 60;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM