I have a problem in this function( int populationTotal(villes ville[], int n, char nom[])
), I've created a structure of city have a name and number of poeple and name of his country, and I want from the user to gives me a name of country and I'll give him the total of the poeple in this country.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ville
{
char nom[50];
int population;
char pays[30];
}villes;
void chargement(villes villes[], int n)
{
int i;
for(i=0; i<n; i++)
{
printf("Entrez le nom de la ville n° %d: \n", i+1);
gets(villes[i].nom);
printf("Entrez la population de la ville n° %d:\n", i+1);
scanf("%d", &villes[i].population);
getchar();
printf("Entrez le pays de la ville n° %d:\n", i+1);
gets(villes[i].pays);
}
}
int populationTotal(villes ville[], int n, char nom[])
{
int Total=0, i;
for(i=0; i<n; i++)
{
if(strcmp(ville[i].pays, nom))
Total += ville[i].population;
}
return Total;
}
int main()
{
villes ville[50];
int n;
char pays[30];
printf("Entrez le nombre de villes: \n");
scanf("%d", &n);
getchar();
if( n < 1 || n > 50)
printf("Le nombre doit etre...");
else
{
chargement(ville, n);
printf("Entrez le pays: \n");
gets(pays);
printf("La population total est: %d", populationTotal(ville, n, pays));
}
}
You're not checking the pays
string correctly:
if(strcmp(ville[i].pays, nom))
The strcmp
function returns 0 if the two strings match and non-zero if they don't match. Since a conditional is considered true if it evaluates to non-zero, the if
portion is only entered when pays
does not match each ville[i].pays
. And because you entered the same pays
string for each village as well as the separate pays
string, they all match so the if
condition is never entered.
If you entered a different pays
for one village then the if
would be entered for that one and you would get a non-zero return value from the function.
You need to compare the result of strcmp
with 0 to see if the strings match.
if(strcmp(ville[i].pays, nom) == 0)
Also, never use gets
but instead use fgets
.
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.