将字符串与 2D 数组进行比较

Comparing a String with 2d Array

本文关键字:比较 数组 2D 字符串      更新时间:2023-10-16

实际上我正在尝试将字符串与 2d 数组进行比较。如果输入的字符串已存在于数组中,则程序应终止。如果字符串不存在,则应将其存储在数组的下一行中。这段代码所做的是,它不告诉输入的"cnic"之前是否被输入过。我使用的是 Turbo C++ 3.0 编译器,所以请记住这一点。

该程序实际上获取用户的cnic,并检查该cnic之前是否已输入。

这是我的程序

          cout<<"nEnter Your CNIC?n";
        gets(cnic);
        **for (i=0;i<=13;i++)
        {
            if (strcmp(cnic,cnic2)==0)
            {
                cout<<"This Cnic has already casted the vote";
            }
        }
        cnic2[i][j]=cnic[i];
        j++;**

我使用了 Turbo C(甚至不是 ++),但它很久以前......更严重的是,我假设:

  • cnic 是大小为 13(12 + 终止空值)的 char 数组
  • cnic2 应该是一个包含 100 个字符数组的 2D 数组,大小为 13(它不是代码中编写的内容)
  • 你想看看cnic C 字符串是否已经在 cnic2 中,如果是,你拒绝它,如果不是,你添加它。
  • jcnic2 中下一个元素的索引,应该在主循环之前明确设置为 0。

声明:

char cnic2[100][13];
int found; /* should be bool found but unsure if Turbo C++ knows about that */

(您的代码声明了一个大小为 100 的 13 个 C 形环的数组)

测试

循环(包括OP审查和测试的代码):

/* should control size of nic before that processing - I ASSUME IT HAS BEEN DONE */
found = 0;  /* should be found = false; and later use false and true instead of 0 and 1 */
for(i=0; i<j; i++) {
    if (0 == strcmp(cnic, cnic2[i]) {
        found = 1;
        break;
    }
}
if (found) {
    cout<<"This Cnic has already casted the vote";
    continue;
}
if (j == 99) {
    count << "Too much Cnic already";
    break;  
}
strcpy(cnic2[j++], cnic);

/* Revised and Working Code
found = 0;  /* should be found = false; and later use false and true instead of 0 and 1 */
for(i=0; i<j; i++) {
    if (0 == strcmp(cnic, cnic2[i]))
    {
        found = 1;  
        break;
    }
}
if (found) {
    cout<<"This Cnic has already casted the vote";
    continue;  
}
if (j == 99) {
    cout << "Too much Cnic already";
    break;   
}
strcpy(cnic2[j++], cnic);
专注于

您用**标记的代码。 错误编号如下:

for (i=0;i<=13;i++) // (1)
{
    if (strcmp(cnic,cnic2)==0)  // (2)
    {
        cout<<"This Cnic has already casted the vote";
    }
}
cnic2[i][j]=cnic[i]; // (3)

对于错误(1),你循环了太多次。 您想从 0 循环到 12,或使用 < 13 ,而不是<= 13

对于错误(2)strcmp()的第二个论点是错误的。 您想要比较从 cnic2[j] 开始的字符串。

对于错误(3),您正在访问两个数组的越界元素,因为i将是 13。

我不会为您修复这些,因为您的代码可以执行更多操作。 我指出的答案显然是错误的。