0

This code below is searching name from the string, user has given input of 7 names and then the program asks the user to enter the name, program is then performing search from an array and output the position of the name. The program stops asking user if the user press n otherwise it would continue to ask the user to search. This program is working fine but only finds exact matches. The program should ignore capital character and small character but it is not ignoring. for example array contains the name "JAMES" and I search james it will not give me position . This is my program below please help how to do this. Thanks

#include <iostream>
#include <string>
using namespace std;


int main(){

string str[7];
string search;

for(int i=0; i<7; i++){
    cin>>str[i];
}


//searching the string

cout<<endl;


char option;
do{
    cout<<"Enter the name to search"<<endl;
    cin>>search;

        for(int i=0; i<7; i++){
            if(str[i]==search){
                cout<<search<<" has been found in the "<<i+1<<" Position"<<endl;
            }

        }
cout<<"Do you want to search another name, press y to continue or n to just quit"<<endl;
cin>>option;


}while(option!='n');



return 0;
}
Deanie
  • 2,316
  • 2
  • 19
  • 35
user3100177
  • 65
  • 1
  • 9

2 Answers2

0

you have not added the logic yet to ignore Case (upper or lower) , for that , you would need to convert the input string as well as the stored strings to either all uppercases or all lowercase and then compare.

a simple snippet which can convert string to uppercase is :

for(int i = 0; i < strlen(s); i++)
   s[i] = toupper(s[i]);

(a better way would be to convert the string to uppercase while inputting, so that when the user inputs the value to be searched , you need to convert only this value to uppercase)

gaurav5430
  • 12,934
  • 6
  • 54
  • 111
0

Make your own function for case-insensitively comparing strings:

// You must include <cctype> to use std::toupper
bool ci_compare(std::string const & s1, std::string const & s2)
{
    // If both strings have different lengths, then they
    // are different. End of the story.
    if (s1.size() != s2.size()) return false;

    // Asserting that two strings are case-insensitively equal
    // is the same as asserting that the result of converting
    // both strings to uppercase are (case-sensitively) equal.
    auto i1 = s.begin(), i2 = s2.begin(), e = s1.end();
    while (i1 != e)
      if (std::toupper(*i1++) != std::toupper(*i2++))
        return false;
    return true;
}

Then, in the snippet you posted, replace

if (str[i] == search) {

with

if (ci_compare(str[i], search)) {
isekaijin
  • 19,076
  • 18
  • 85
  • 153