簡體   English   中英

strcmp如何用於二維數組?

[英]How does strcmp work for 2d arrays?

我正在嘗試查看strcmp函數如何在C中用於2d數組。 假設我已經使用2d數組讀取了4個字符串。 數組中的“ 4”是字符串的數目,數組中的“ 20”是字符串的最大長度。 我應該要求用戶輸入放置在對象2d數組中的對象,但是我對其進行了硬編碼,以使您更容易理解問題。

2d數組聲明為

char objects[4][20] = {{Can},
                       {Laptop},
                       {Bag},
                       {Board}};


//The above code is the 2d array containing four strings

int i;
char target[5][20];

printf("Enter the object you want to search for: \n");
scanf("%s", &target);


int check = 0;
check = strcmp(target, objects);
//printf("Check: %d\n", check);//I was trying to print check itself to know 
//what the value actually is

if (check == 0)
{
    printf("Yes the object you searched is among the list");
}
else
{
    printf("No sorry, the object you searched is not among the list");
}

請讓我知道我是否做錯檢查,因為無論何時我搜索“ Can”,輸出都會顯示該對象不在列表中,但是當我搜索任何其他對象時,它將顯示該對象在列表中Can之后列表中的對象。

看來您的意思是以下內容

char objects[][20] = { "Can", "Laptop", "Bag", "Board" };
const size_t N = sizeof( objects ) / sizeof( *objects );

char target[20] = "Bag";

size_t i = 0;

while ( i < N &&  !( strcmp( objects[i], target ) == 0 ) ) i++;

if ( i != N)
{
    printf("Yes the object you searched is among the list");
}
else
{
    printf("No sorry, the object you searched is not among the list");
}

也就是說,您將確定在字符串的二維字符數組中是否存在給定的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM