繁体   English   中英

C:使用字符串数组时的空白输出

[英]C : Blank output while using array of string

所以我尝试使用 c languange 为管理员创建用户名和密码,在此处的代码中,数组 inpstring 的索引确定什么是用户名和密码,偶数(和 0)是用户名,奇数是密码。

#include <stdio.h>
#include <string.h>

void Listofadmins(int index, char inpstring[][50]){
    if(index == 0){
        strcpy(inpstring[0], "Carl01");
        strcpy(inpstring[1], "SVm6u&N591s2");
    } else if(index == 1){
        strcpy(inpstring[2], "Devoth754");
        strcpy(inpstring[3], "eeKS7@8%0@T6");
    } else if(index == 2){
        strcpy(inpstring[4], "David439");
        strcpy(inpstring[5], "l$z7eqV2aD00");
    } else if(index == 3){
        strcpy(inpstring[6], "Matt208");
        strcpy(inpstring[7], "h9Je2#Ri3or$");
    }
}

void main()
    {
    int j, k = 0, y = 1;
    char str[100][100];
    for(j = 0, k, y; j < 4; j++, k += 2, y += 2){
        listofadmins(j, str[10]);
        printf("%s\n%s", str[k], str[y]);
    }
}

当我尝试运行代码时,没有输出,只有空白。 我以为listofadmins函数会将inpstring数组中的字符串复制到主程序数组str中。 你知道问题出在哪里吗?

几个问题...

  1. 为此使用二维数组是有问题的。 最好创建一个struct
  2. Listofadmins中与strcpy一起做一个if/else阶梯是不必要的复杂
  3. 使用固定大小的char数组而不是char *会使事情复杂化。

这是一些简化的代码:

#include <stdio.h>
#include <string.h>

struct user {
    const char *user;
    const char *pw;
};

struct user users[] = {
    { "Carl01", "SVm6u&N591s2" },
    { "Devoth754", "eeKS7@8%0@T6" },
    { "David439", "l$z7eqV2aD00" },
    { "Matt208", "h9Je2#Ri3or$" }
};

int
main(void)
{

    for (size_t i = 0;  i < sizeof(users) / sizeof(users[0]);  ++i) {
        struct user *user = &users[i];
        printf("User: %s Pw: %s\n",user->user,user->pw);
    }

    return 0;
}

这是程序输出:

User: Carl01 Pw: SVm6u&N591s2
User: Devoth754 Pw: eeKS7@8%0@T6
User: David439 Pw: l$z7eqV2aD00
User: Matt208 Pw: h9Je2#Ri3or$

我更改了 'listofadmins' 的调用参数以匹配将inpstring[][50]截断为inpstring[][100]的 'str' 的声明。 在调用函数时,我删除了 'str' 之后的括号,因此str[10]变成了str

结果代码是这样的

#include <stdio.h>
#include <string.h>

void listofadmins(int index, char inpstring[][100]){
 if(index == 0){
     strcpy(inpstring[0], "Carl01");
     strcpy(inpstring[1], "SVm6u&N591s2");
 } else if(index == 1){
     strcpy(inpstring[2], "Devoth754");
     strcpy(inpstring[3], "eeKS7@8%0@T6");
 } else if(index == 2){
     strcpy(inpstring[4], "David439");
     strcpy(inpstring[5], "l$z7eqV2aD00");
 } else if(index == 3){
     strcpy(inpstring[6], "Matt208");
     strcpy(inpstring[7], "h9Je2#Ri3or$");
 }
}

void main()
{
int j, k = 0, y = 1;
char str[100][100];
for(j = 0, k, y; j < 4; j++, k += 2, y += 2){
    listofadmins(j, str);
    printf("%s\n%s", str[k], str[y]);
}
}

输出是:

Carl01
SVm6u&N591s2Devoth754
eeKS7@8%0@T6David439
l$z7eqV2aD00Matt208
h9Je2#Ri3or$

我可能会建议更改 printf 以获得更好的可读性。 希望我能帮忙。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM