如何比较 C 中的两个字符串,比较的字符数是从文件接收的字符串中的字符数

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

我正在尝试用 C 创建一个具有唯一登录名的“银行”程序,为此,我有一个用户名文件,并检查用户输入的用户名是否与预先存在的用户名相匹配,并在下面进行了操作

    FILE *pF = fopen("usernames.txt", "a+"); //opens 2nd file to read it, and creates it if it doesn't exist
    
    //int length = sizeof(userName) / sizeof(userName[0]);
    while (fgets(buffer, 255, pF)) { //reads file adn checks if the username is on it
        if (strncmp(buffer, userName, strlen(userName)) == 0) { //checks the amount of characters in the string userName and only compares those characters
            uniqueUsername = false;
            break;
        }
    }

但是我的问题是,如果存在预先存在的用户名(例如“Daniel”),则无法创建“Dan”作为另一个用户名。

我尝试将

strlen(userName)
更改为
strlen(buffer)
,但这会比较缓冲区字符串的所有 255 个字符(我将其创建为 255 字节的虚拟数组)并导致不匹配。有什么办法可以解决这个问题吗?

c string char
1个回答
0
投票

在 C 中,您可以使用 库中的 strncmp 函数比较具有特定字符数的两个字符串。我们使用 fgets 将字符串从文件读取到缓冲区数组中。然后使用 strncmp 将字符串与从文件中读取的字符串长度 (strlen(buffer))。如果字符串等于该长度,则结果为 0。 程序根据比较打印字符串是否相等。

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