我试图在程序中使用 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/