将输入数组与字符串进行比较

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

我正在使用 Dev-C++,错误在这一行:

w=strcmp(nama[i],user)

有人知道如何解决这个问题吗?

我建议你研究这个:

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

注意:在理解差异之前,请使用 std::vector 而不是数组,对于任何文本,请使用 std::string。您可以使用 C++ 标准库函数 std::find() 来查看 user 值是否出现在 nama 中,但是学习如何编写循环和自己做事也很好。

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