List of rivers by continent is given. Find average length of rivers on chosen continent. C++

StackOverflow https://stackoverflow.com/questions/23456563

  •  15-07-2023
  •  | 
  •  

Question

I have been trying to solve the problem with the help of structures. Here is what I have by far:

#include <iostream>
#include <iomanip>
#include <conio.h>
#include <time.h>

using namespace std;

struct{
       char name[20];
       char continent[20];
       float length;
       }
       river[15] = {{ "Missisipi", "North America", 5969}, {"Yukon", "North America", 3180}, {"Mackenzie", "North America", 4240},
       {"Amazon", "South America", 6992}, {"Parana", "South America", 4700}, {"Orinoco", "South America", 2600},
       {"Danube", "Europe", 2850}, {"Dnieper", "Europe", 2201}, {"Volga", "Europe", 3530}, {"Yenisey", "Asia", 4102},
       {"Indus", "Asia", 3180}, {"Amur", "Asia", 4440}, {"Nile", "Afrika", 6670}, 
       {"Niger", "Afrika", 4160}, {"Congo", "Afrika", 4320}};

       int main()
       {
           char u[20];
           int i;
           cout << "World's longest rivers: \n";

           for (i=0; i<15; i++)
           {
               cout << setw(20) << river[i].name << setw(20) << river[i].continent << setw(20) << river[i].length << endl;
               }

               cout << "\nEnter name of the continent: ";
               cin >> u;
               cout << "\nChosen continent is:\n";
               for (int i=0; i<15; i++)
                if (river[i].continent == u)
                cout << setw(20) << river[i].name << setw(20) << river[i].continent << setw(20) << river[i].length << endl;
               getch();
               }

Well, there are a couple of questions that bother me:

  1. The code compiles, but when the dos-window showes up, information under the string Chosen continent is: is blank;

  2. I wonder how I could solve average length of rivers on chosen continent.

The primary problem I have found at this line:

 if (river[i].continent == u)

The comparison never yields true.

Was it helpful?

Solution

In this line

if (river[i].continent == u)

you are comparing two char* pointers (wich will never have the same value for sure).
You probably want to do

if (strncmp(river[i].continent,u,sizeof(u)) == 0)

to check if the character arrays pointed have the same content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top