سؤال

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.

هل كانت مفيدة؟

المحلول

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;
}
}

نصائح أخرى

strcmp function takes 2 parameters of type const char*. While const char* is implicitly convertible to std::string, it is not the other way around.

You can get a pointer to internal char array by c_str member function:

strcmp(name, firstnames[0][0].c_str());

or you can make a string from name and use operator==

if (std::string(name) == firstnames[0][0]) // ...

By the way, this:

char name[100];
cin >> name;

is pretty vulnerable to buffer overflows. What if the user enters more than 100 characters? I'd suggest you use std::string from the start.

The problem is that you have defined your courses as type "string" but are accessing them like a "char*" (or in your case "char[]" which is pretty much the same thing). All you would need to do is change this line:

if (strcmp(name, courses[0][0]) == 0)

to this:

if (strcmp(name, courses[0][0].c_str()) == 0)

Note the "c_str()". This simply returns a char* pointer of your string which can be used in strcmp().

As an aside: is there any particular reason you have gone from using std::string to char*? The reason I ask is because char* is more of a C-style way to program. The std:string type was designed for C++ and contains built in comparison operators for other strings (and I believe even char*s). Generally when programming in C++, it's best to use C++ style types whenever possible as there are a lot of advantages (RAII memory managements, standard algorithms, utility methods, etc...).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top