C:使用scanf将“字符串”放入char数组时,char数组中的其他char,

问题描述 投票:0回答:1

我遇到一个关于字符串(字符数组)比较的问题。下面的代码不是我的程序,而是我在做什么的模拟。我有一个结构,其中存储项目的名称。后来我让用户使用输入名称搜索项目,它将结构项的实例名称(例如Xenon)与该用户输入相匹配。但是,输入字符串包含乱码,我将显示。我在字符的末尾添加了“ \ 0”,因此这不是问题,除非我做错了。更清楚地说,用户输入“氙气”,因此我们找到了struct Item的实例,名称为“氙气”。

// Section #A
// I store structs in this dynamically allocated array. 
// Later, users can access item instances, if needed.
struct Item *struct_arr = malloc( sizeof(struct Item)*SIZE );

struct Item
{
        char name[16];
        float price;
        int quantity;
        int id_num;
};
struct Item item1;
strcpy(item1.name, "Xenon"); // i explicitly set this instance 
item1.price = 125; 
item1.quantity = 2;
item1.id_num = 1;
struct_arr[0] = item1;

// Section #B
char name[16]; // also tried 17
name[16] = '\0'; // or 17, tried 17
scanf("%s", name); // assume I enter, "Xenon"
// res outputs 2
int res = strcmp(item1.name, name); // They are not the same, though when printed, "Xenon" and "Xenon"


// THE ISSUE IS BELOW : THE SOLUTION IS SET strcmp == 0
for (int i=0; i < SIZE; i++) {
           if (strcmp(struct_arr[i].name, name)) { // strcmp(struct_arr[i].name, name) == 0

                   int res = strcmp(struct_arr[i].name, name); * #A                   

                   break;
           }

 }
// i then proceeded to gdb to see what was going on. Read on

在gdb中,我走到程序中我正在使用用户的输入(存储在char数组“名称”中)选择正确的结构Item实例。

Gdb给出如下结果:印刷名称“氙气\ 000 \ 000 \ 000 \ 372 \\ 367 \ 377 \ 177 \ 000”打印item1.name“氙气\ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000 \ 000”

这可能很麻烦,但是我将包含C的printf结果。此结果同时查看并行字符。那是,从i = 0到i <16,它查看item1.name [i]和name [i]。

// Output is i, item1.name[i], name[i]
each: i is 0,X,X
each: i is 1,e,e
each: i is 2,n,n
each: i is 3,o,o
each: i is 4,n,n
each: i is 5,,
each: i is 6,,
each: i is 7,,
each: i is 8,,▒
each: i is 9,,G
each: i is 10,,▒
each: i is 11,,▒
each: i is 12,,A
each: i is 13,
each: i is 14,,
each: i is 15,,

显然,这两个字符串不相同。用户输入的字符串中包含一些乱码,而item1.name的字符串看起来相当“干净”。

我不确定是什么问题。我的逻辑是,尽管name [16]不在我保留的内存中,如果我们在名称[15]之后放置'\ 0',那么如果在名称上进行迭代时确实点击了'\ 0'我们仍然会遇到该内存位置,因为15和16在内存中相邻。我认为这不是问题。

此外,当我设置item1的属性“名称”时,它会在我的知识中隐式地添加“ \ 0”,因为我们要给字符串char名称[16]分配一个字符串“”,而不是char“。 C对此进行了抽象。

话虽如此,我还是不完全确定问题是什么。

c arrays char scanf
1个回答
0
投票

[似乎我忽略了与“ strcmp(a,b)”进行比较时忽略了“ == 0”的事实。睡眠很重要。这就是这篇文章所教的。感谢所有寻找我在第一版中没有提到的问题的人。道歉。

© www.soinside.com 2019 - 2024. All rights reserved.