0

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?

2
  • 5
    Are you trying to create five strings? And what do you think cin>>user[30]; does? And your for loop makes no sense. Basically, most of your code makes no sense, and without comments, we have no way to know what it's supposed to do. Commented Oct 5, 2015 at 8:12
  • Is this a real code and a real location of error? And what is an error? Commented Oct 5, 2015 at 8:14

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
`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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.