简体   繁体   English

加载 C 不正确

[英]Loading in C doesn't come out right

Below is my simple code, in which I am trying to make a loading animation, but the output seems to be unrelated to what is expected.下面是我的简单代码,我在其中尝试加载 animation,但 output 似乎与预期无关。 Please assist me in pointing out my mistakes, as I am new to C.请帮助我指出我的错误,因为我是 C 的新手。

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

LO();
main(){
    LO();
}

LO(){
    char ad = '-';
    int n   = 1;
    while (n<10){
        printf(" %c >", ad);
        Sleep(1000);
        ad += n*'-';
        n++;
    }
}

The output: output:

 - > Z > ┤ > ; > ∩ > ╨ > ▐ >  > ü >

What I expected:我所期望的:

-> ->

then clear screen然后清屏

--> -->

then clear screen然后清屏

---> --->

and more till a certain times.直到特定时间。

then clear screen然后清屏

C is not Python. C不是Python。 It does not have n * string concatenation.它没有n *字符串连接。

This line:这一行:

ad += n*'-';

ad has a numeric ASCII value of 45 at first. ad 最初的数字 ASCII 值为 45。 The literal '-' is also 45. You expect that you concatenate n * '-' to the string but you are just doing numeric calculations.文字 '-' 也是 45。您希望将 n * '-' 连接到字符串,但您只是在进行数字计算。

So when n == 1 you add 45 to 45 which is ASCII 'Z', and that's what you see in your output.因此,当n == 1时,您将 45 添加到 45,即 ASCII 'Z',这就是您在 output 中看到的内容。

When you want to concatenate in C you use strcpy , strcat .当您想在 C 中连接时,您可以使用strcpystrcat

A rather hacky way to do this would be the %.*s format specifier for printf.一个相当老套的方法是 printf 的 %.*s 格式说明符。

const char *fullline = "---------------------------------";
for (int i = 1; i < 10; i++)
    printf("%.*s\n", i, fullline);

printf cuts off fullline after i characters. printf 在 i 个字符后切断整行。

One approach would be to use a for loop:一种方法是使用for循环:

void LO(void)
{
    int n = 1;

    while(n < 10)
    {
        for(int i = 0; i < n; i++)
            printf("-");
        printf(">");

        Sleep(1000);

        printf("\r");
        fflush(stdout);

        n++;
    }
}

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

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