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

时间:2015-10-05 08:09:43

标签: c++ dev-c++

如何使用正确的代码将输入数组与字符串进行比较?

#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)

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

2 个答案:

答案 0 :(得分:1)

我建议你研究一下:

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()来查看usernama值是否出现,但是学习如何编写循环以及自己做的事情也很好。

答案 1 :(得分: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);
    }
}