Search code examples
c++arraysmultidimensional-arrayintellisensestrcmp

C++ 2d array search error


I'm trying to search a 2d array for a string.

The 2d array contains names and birthdays.

I want to search a name and display their birthday.

When I try to use strcmp to see if the inputted name compares to any in the array I get this error:

    IntelliSense: no suitable conversion function from "std::string" to "const char *" exists

Here is the bit of code I have:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{

char name[100];

string firstnames[2][4]= { {"John", "Emily", "Juan", "Sally"},
{"Nov 6", "Jan 13", "Oct 10", "Mar 29"} };

cout << "Enter a name: \n";
cin >> name; 

if (strcmp(name, firstnames[0][0]) == 0)
{

}
}

I don't understand how to fix this error? I had another similar error, but it went away when I changed the name to a char array instead of a string. So, I think it has something to do with that, but I don't know what to do to compare the inputted name to the array to find a match.


Solution

  • Since you're already using the string class, why not just make name a string object

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
    
    string name;
    
    string courses[2][4]= { {"John", "Emily", "Juan", "Sally"},
    {"Nov 6", "Jan 13", "Oct 10", "Mar 29"} };
    
    cout << "Enter a course name: \n";
    cin >> name; 
    
    if (name == courses[0][0])
    {
        cout << "Done!" << endl;
    }
    }