Correct my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <string>
using namespace std;
string responce;
int main ()
{
    int array[4][4] = {
    {   0,  95, 173, 103 },
    {  95,   0, 101, 192 },
    {  173, 101, 0, 255  },
    {  103, 191, 255, 0  },
    };





cout <<"***Program that calculate distance b/w 2 cities***" <<endl;
cout <<"\t Barcelona y Tarragona" <<endl;
cout <<"\t Tarragona y Lleida"<<endl;
cout <<"\t Lleida y Girona" <<endl;
cout <<"\t Girona y Barcelona" <<endl;



string responce;
cout <<"\t Select 2 cities:" <<endl;
cin >> responce;
for (int i = 0; i < responce.length(); i++) {
responce[i] = toupper (responce[i]);
}
if (responce == "Barcelona y Tarragona") {
    cout << " Total Distencia = " ;
    cout<<array[0][1]<<endl;
}
else if (responce == "Tarragona y Lleida")
{
    cout << " Total Distencia = " ;
    cout<<array[0][2]<<endl;
}
else if (responce == "Lleida y Girona"){
    cout << " Total Distencia = " ;
    cout<<array[0][3]<<endl;
}
else if (responce == "Girona y Barcelona"){
    cout << " Total Distencia = " ;
    cout<<array[0][4]<<endl;
}
else
    cout <<"Incorrect name Try again!"



system ("pause");
}


I am able to Compile it but it not shows the out put i.e: if i write Barcelona y Tarrgona the result should be 95 but it not shows the result !

Please correct it! if someone write incorrect city name what will be the code after else.
You are converting the input string to all uppercase on lines 29/30 but then comparing the string to mixed case versions, so you'll never find a match.

any correction ?

i m new in C++
Well, either don't convert the input to uppercase (ie, remove that code) or compare the response against, eg, "BARCELONA Y TARRAGONA".
every time it shows

Incorrect name Try again
You cannot accept a string with spaces using cin!! It will just take the first word "BARCELONA" instead of "BARCELONA Y TARRAGONA".

To check try displaying 'responce' after you accept it using cin(some debugging skills!)
cout <<"\t Select 2 cities:" <<endl;
cin >> responce;
cout<<responce;

I would suggest you to use gets() function in library string.h

Also its not the best idea to use "==" for comparing two strings. Try using strcmp() function instead

Topic archived. No new replies allowed.