2013-11-09 3 views
0

Я пишу программу структуры данных в C++, но удивительно, что структура не является моей причиной печали. В моей программе, размещенной ниже, у меня есть два других утверждения if, которые не отображаются в моем выпуске, даже когда их условия выполнены. ОниПроблема с if, else if statement

else if (response == n) 
    cout << "Thank you, goodbye" << endl; 

и

else if (response ==n) 
    cout << "\n" << endl 

Это все дело

// array of structures 
#include <iostream> 
#include <string> 
#include <sstream> 
using namespace std; 

#define NUM_MOVIES 6 
//structure 
struct movies_iit{ 
    string title; 
    int year; 
} films [NUM_MOVIES]; 

//global variables 
char title [20]; 
int y = 1, n = 0, year; 
string search; 

//function 1 
void sort_on_title(movies_iit films[], int n) 
{ 
    //Local struct variable used to swap records 
    movies_iit temp;  

    for(int i=0; i<n-1; i++) 
    { 
     for(int i=0; i<n-1; i++) 
     { 
      /*If s[i].title is later in alphabet than 
      s[i+1].title, swap the two records*/ 
      if(films[i].title>films[i+1].title) 
      { 
       temp = films[i]; 
       films[i] = films[i+1]; 
       films[i+1] = temp; 
      } 
     } 
    } 
} 
//end function 1 
//function query1 prototype 
void query1 (movies_iit movie); 
//function query2 prototype 
void query2 (movies_iit movie); 
//function 2 prototype 
void printmovie (movies_iit movie); 
//beginning of main 
int main() 
{ 
    string mystr; 
    int n; 
    char response; 

    for (n=0; n<NUM_MOVIES; n++) 
    { 
     cout << "Enter title: "; 
     getline (cin,films[n].title); 
     cout << "Enter year: "; 
     getline (cin,mystr); 
     stringstream(mystr) >> films[n].year; 
    } 
    //sort records, function 1 call 
    sort_on_title(films, NUM_MOVIES); 
    cout << "\nYou have entered these movies:\n"; 
    for (n=0; n<NUM_MOVIES; n++) 
     printmovie (films[n]); //function 2 call 
    //Query 1 
    cout << "Perform an alphabetical search? (y/n)" << endl; 
    cin >> response; 

    if (response == y) 
    { 
     cout << "Please enter title" << endl; 
     cin >> title; 
     for (n=0; n<NUM_MOVIES; n++) 
     { 
      query1 (films[n]); 
      response == n; 
     } 
    } 
    else if (response == n) 
     cout << "\n" << endl; 
    else 
     cout << "invalid entry" << endl; 
    //Query 2 
    cout << "Perform a chronological search? (y/n)" << endl; 
    cin >> response; 
    //greater than 
    if (response == y) 
    { 
     cout << "greater than what year?" << endl; 
     cin >> year; 
     for (n=0; n<NUM_MOVIES; n++) 
     { 
      query2 (films[n]); 
     } 
    } 
    else if (response == n) 
     cout << "Thank you, goodbye." << endl; 
    else 
     cout << "invalid entry" << endl; 
    system("pause"); 
    return 0; 
} 
//end of main 
//function 2 definition 
void printmovie (movies_iit movie) 
{ 
    cout << movie.title; 
    cout << " (" << movie.year << ")\n"; 
} 

//function query1 defintion 
void query1 (movies_iit movie) 
{ 
    if (movie.title == title) 
    { 
     cout << " >> " << movie.title; 
     cout << " (" << movie.year << ")\n"; 
    } 
    else 
    { 
     cout << movie.title; 
     cout << " (" << movie.year << ")\n"; 
    } 
} 

//function query2 definition 
void query2 (movies_iit movie) 
{ 
    if (movie.year >= year) 
    { 
     cout << movie.title; 
     cout << " (" << movie.year << ")\n"; 
    } 
} 

Идея заключается в том, чтобы сделать своего рода мини-базы данных фильмов. Код действительно отлично работает, за исключением того, что оператор else if, казалось бы, проигнорирован. Может ли кто-нибудь объяснить, почему это так?

ответ

0

response - char тип. Поместите 'y' и 'n' в одинарных кавычках:

if (response == 'y') 
... 
... 
else if (response == 'n') 
    cout << "\n" << endl; 
+1

Я был удивлен, это даже компилируется, пока я не заметил переменный вопрос рамочного: OP имеет глобальный «Int N», а также местный «Int N» для цикла, плюс глобальный 'int y'. Никогда не используйте значения int для символа, которые соответствуют, и сделайте свои имена переменных описательными, и вы бы не увидели эту ошибку в первую очередь! – thinkOfaNumber