将字符串与 2D 数组进行比较
Comparing a String with 2d Array
实际上我正在尝试将字符串与 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
中,如果是,你拒绝它,如果不是,你添加它。 -
j
是cnic2
中下一个元素的索引,应该在主循环之前明确设置为 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。
我不会为您修复这些,因为您的代码可以执行更多操作。 我指出的答案显然是错误的。
相关文章:
- 比较字符数组
- For 循环仅比较数组的第一部分而不是整个数组
- C 比较数组中的元素并打印位置
- 如何在C++中比较数组中字符串的一部分的字符串
- 通过比较数组中的相邻元素来计算交换次数
- 在同时添加和删除匹配项的同时比较数组中的项
- 在 C++ 中比较数组的元素
- 比较数组C++中单词列表中的单词
- 如何使用 == 运算符来比较数组的元素
- 比较数组中的随机值
- 警告:在 C++ 中比较数组和字符串
- 如何在Qt单元测试中比较数组
- 比较数组的最佳方式
- 如何比较数组内部的值
- 如何用C或C++比较数组中的内容
- 比较数组的所有元素
- 比较数组中的值并删除较大的值
- 快速比较数组和数字
- 比较数组中的项
- C++ 比较数组中的两个值并获取更大的下标数