c - 查找数组的大小和单词洗牌

标签 c string size

我试图在程序中使用 size_t 查找字符串的长度,然后使用该整数来确定程序循环执行字母洗牌的次数(+6 到字母,因此保存时 a = g)。

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

int main(void)
{
    FILE *file;
    int i, fnlen, lnlen;
    char firstname[15], lastname[15],  *ptr;

    fflush(stdin);
    printf("Please enter the first name of the player:");
    if(fgets(firstname, sizeof(firstname), stdin) != NULL)
    {
        size_t fnlen = strlen(firstname);
    } 
    printf("Please enter the last name of the player:");
    if(fgets(lastname, sizeof(lastname), stdin) != NULL)
    {
        size_t lnlen = strlen(lastname);
    }

    for(i = 0; i < lnlen; i++)
    {
        lastname[i] = (char)((lastname[i] - 'a' + 4) % 26 + 'a');    
    }
    for(i = 0; i < fnlen; i++)
    {
        firstname[i] = (char)((firstname[i] - 'a' + 4) % 26 + 'a');        
    }

    file = fopen("text.txt", "wt");
    if(!file)
    {
        printf("File is not able to open.");
        exit(1);
    }
    fprintf(file, "Firstname is : %s\n""Lastname is: %s\n", firstname, lastname)

当我打开保存到的文件时,名字被正确打乱,但当我输入 5 时有 8 个字符,姓氏被正确保存,但字母没有打乱,它们只是输出我输入的内容fgets

最佳答案

我在代码中看到的主要问题是您在 if 语句内声明了 size_t 长度变量。这样,您对它们所做的任何更改都不会反射(reflect)在 if 语句之外。我很惊讶你的代码编译给出了这个(除非你还在你向我们展示的内容之上声明了另一个 size_t len 和 fnlen 在这种情况下,通过在 if 语句内部重新声明你正在隐藏它。)我会像这样重写代码。我认为您可能在上面声明了它们并将它们初始化为零。在这种情况下,您在 if 语句内声明了一个完全不同的变量(具有相同的名称),它没有效果,并且循环中使用的长度变量仍然具有零值。

printf("Please enter the first name of the player:");
size_t fnlen = 0; //I declare them once outside of the if
size_t len = 0;
if(fgets(firstname, sizeof(firstname), stdin) != NULL)   
{
    fnlen = strlen(firstname); //do not redeclare them inside just assign
} 
printf("Please enter the last name of the player:");
if(fgets(lastname, sizeof(lastname), stdin) != NULL)
{
    len = strlen(lastname);
}
ptr = lastname;
while( *ptr != '\n') ++ptr;    
*ptr = '\0';
for(i = 0; i < len; i++)
{
    lastname[i] = (char)((lastname[i] - 'a' + 6) % 26 + 'a');    
}
for(i = 0; i < fnlen; i++)
{
    firstname[i] = (char)((firstname[i] - 'a' + 6) % 26 + 'a');        
}

关于c - 查找数组的大小和单词洗牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34178112/

相关文章:

python - 段错误 - python C 扩展中的核心转储

python - 从 C 调用 python hello world 函数,解析字符串参数

c - Valgrind "Invalide write of size 1"

objective-c - 用 Swift 和 Objective-C 编写的空项目存档之间的比较

c# - 如何在不增加可执行文件大小的情况下将图像添加到我的桌面应用程序?

c - 将一个变量值赋给另一个变量值

c - 没有内存泄漏

java - 简单Java : How to make string replace and wait then replace again?

Java 正则表达式在 Android 上的工作方式与在 Java 上的工作方式不同

java - 永久增加java堆大小?