Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Question: In a room , there are three students Yuki, Shiro and Kaname. You have to display that their name exists on giving the input.
Also ,please give me the corrected program.

Example:
INPUT:
Enter no of students: 3 (no of students)
Enter name:
Yuki
Shiro
Kaname

Enter name to be searched: Shiro

OUTPUT:
Shiro exists!!

What I have tried:

C++
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
    string s[10], y;
    int i;
    for (i=0; i< 3; i++)
        cin>>s[i];
    cin>>y;
    if (y == s[i])   
        cout<< y << " exists";
    else
        cout<< y <<"Does not exist";
    return 0;
}
Posted
Updated 16-Oct-20 6:39am
v5

You have two main problems. Firstly you are including <string.h> which is the old C library header; it should be just <string> for the standard template library.
Secondly, you compare the search field with a blank string, instead of searching each in turn, so the search entry will never be found.
C++
    if (y == s[i])   // at this point i == 3, so s[i] has no value
        cout<< y << " exists";

// you should write:
    for (i=0; i < 3; i++)
    {
        if (y == s[i])
        {
            cout << y << " exists";
            break;
        }
    }
    if (i == 3)
        cout << y <<" Does not exist"; // loop terminated without finding the key
 
Share this answer
 
You forgot a loop:
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s[10], y;
    int i;
    for (i=0; i< 3; i++)
        cin>>s[i];
    cin>>y;

  for (i=0; i<3; ++i) // use a loop for searching in all the entered items
  {
    if (y == s[i])
    {
      cout<< y << " exists";
      return 0;;
    }
  }
  cout<< y <<" does not exist";
}


Please note: C++ STL gently provides the set[^] class:
C++
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main()
{
  set<string> folks;

  for (int i=0; i< 3; i++)
  {
    string new_member;
    cin >> new_member;
    folks.insert(new_member);
  }

  string name_to_search_for;
  cin >> name_to_search_for;

  cout << name_to_search_for;
  if ( folks.find(name_to_search_for) == folks.end())
    cout << " not";
  cout << " found." << endl;
}
 
Share this answer
 
v4
Just add code for what is actually missing according to the example:

  • Print the prompt texts (number of students, name to be searched) so that the user knows what to enter
  • Read the number of names to be entered
  • Print the result as shown in the example (it includes the entered name)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900