Reputation: 13
How can use the proper code to compare an input array with string?
#include<iostream>
#include<cstring>
#include<stdlib.h>
using namespace std;
int main()
{
char user[30] ;
string nama[5]="ali33,abu123,ahmad456,kasim123,rahmat123";
int w,i ;
cout<<"username : ";
cin>>user[30];
for(i=0;i>=0;++i)
{
w=strcmp(nama[i],user);
}
I'm using Dev-C++, and the error is on this line:
w=strcmp(nama[i],user)
Does anyone know how to fix this?
Upvotes: 0
Views: 847
Reputation: 319
`strcmp()`**is used when comparing c-string data types. Convert your char data type to string and use compare function as illustrated below**`
int main()
{
char user[30];
string nama[5] = { "ali33","abu123","ahmad456","kasim123","rahmat123" };
int w = -99;
int i;
cout << "username : ";
cin >> user[30];
string temp(user);
for (i = 0; i < 5; i++)
{
w = nama[i].compare(temp);
}
}
Upvotes: 0
Reputation: 106076
I suggest you study this:
std::vector<string> nama = { "ali33", "abu123", "ahmad456",
"kasim123", "rahmat123" };
string user;
cout << "username : ";
int w = -1;
if (cin >> user)
{
for(int i = 0; i < nama.size(); ++i)
if (nama[i] == user)
w = i;
if (w != -1)
std::cout << user << " found at [" << w << "]\n";
else
std::cout << user " not found\n";
}
Notes: use std::vector
not arrays until you understand the differences, and std::string
for any text. You could use the C++ Standard Library function std::find()
to see if the user
value appears in nama
, but it's good to learn how to write a loop and do things yourself too.
Upvotes: 1