c - 为什么我的 strlen 似乎在这个 for 循环中返回两个值?

标签 c for-loop strlen

基本上,我正在尝试使用我的 C 语言(基本)知识来创建 d&d 骰子滚筒。在 for 循环中,该循环应该循环输入并返回骰子的边数骰子,strlen() 似乎返回两个单独的值:1. 正确的值,2. 一个非常大的数字。我无法弄清楚为什么它返回第二个数字,这会弄乱 for 循环。

我尝试将 strlen() 分配给另一个名为 length 的变量,并在使用 strlen() 的函数中调用该变量。每次我在存在输入 dice_inp 的函数中打印 strlen() 时,它都会打印正确的值,但是一旦我将其传递给 sides() code> 它返回极大的数字。

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

int num();
int sides();

int main()
{
    printf("This is a dice rolling simulator for D&D!\n");
    int num_dice, num_sides;
    num_dice = num();
    num_sides = sides();
    printf("num %d sides %d", num_dice, num_sides);
}

int num()
{
    int i, keynum, dice_num = 0, length;
    char dice_inp[20];

    printf("Input the number of dice(n), then d,then the number of sides of each dice(s) so the input appears n the form 'nds'!\n");
    scanf("%s", dice_inp);
    length = abs(strlen(dice_inp));

    keynum = strcspn(dice_inp, "d");

    for (i = 0; i < keynum; i++)
    {
        char c = dice_inp[keynum - 1 - i];
        c = c - '0';
        c = round(c*pow(10, i));
        dice_num += c;
    }

    if (dice_num == 1)
    {
        printf("There is %d dice being rolled.\n", dice_num);
        Sleep(500);
    }

    else if (dice_num == 0)
    {
        printf("You cannot roll 0 dice.\n");
        Sleep(500);
        num();
    }

    else if (dice_num > 1)
    {
        printf("There are %d dice being rolled.\n", dice_num);
        Sleep(500);
    }

    Sleep(500);
    sides(length, dice_inp, keynum);
    return dice_num;
}

int sides(int length, char dice_inp[], int keynum)
{
    int i, dice_sides = 0;

    for (i = 0; i < abs((length - keynum - 1)); i++)
    {
        char c = dice_inp[strlen(dice_inp) - 1 - i];
        c = c - '0';
        c = round(c*pow(10, i));
        dice_sides += c;
        printf("a");
    }

    if (dice_sides == 1)
    {
        printf("A dice cannot have one side. Please try again!\n");
        Sleep(500);
        num();
    }

    else if (dice_sides == 0)
    {
        printf("A dice cannot have 0 sides. Please try again.\n");
        Sleep(500);
        num();
    }
    else if (dice_sides > 1)
    {
        printf("The dice will have %d sides.\n", dice_sides);
        Sleep(500);
    }

    printf("%d", dice_sides);
}

最佳答案

你的代码有很多问题。 首先,函数“sides”定义如下:

int sides(int length, char dice_inp[], int keynum);

但你调用它时不带参数

num_sides = sides();

当你得到一个无效的输入时,在函数“num”中,你再次递归地调用它,这会导致堆栈的浪费。最好使用循环。在同一个函数中,当您递归调用它时,您会丢失返回值。这意味着最终您会得到错误的值。该函数中的“ sleep ”函数对我来说毫无意义。

我猜测 strlen 的问题与输入字符串不包含终止符有关。尝试使用 printf 来跟踪 strlen 之前的输入。

我在这里描述的问题并不是唯一的问题。

关于c - 为什么我的 strlen 似乎在这个 for 循环中返回两个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56123167/

相关文章:

c - 如何在不使用strlen的情况下计算字符串的字符数

php - 用 strlen 替换

c - 如何使用指针打印二维数组

c - 使用 getc 获取奇怪的字符?

php - 嵌套 for 循环给出不相关的输出

matlab - 随时间执行for循环

c - 是否仍然值得在 OpenMP 实现上投入时间?

c - 无法使用 fork 退出子进程

javascript - 函数式编程 - 递增计数器的简单 For 循环

c - strlen 没有返回正确的字符数