小编Ran*_*vas的帖子

将元素从一个字符数组复制到另一个字符数组

我想将字符串中的元素转移到另一个字符串,因此编写了以下程序.最初,我认为for循环应该执行,直到复制了NULL字符(包括它).但是在这段代码中,如果找到一个NULL字符(即尚未复制),for循环终止,但它仍然能够显示已复制元素的字符串.如果首先没有NULL字符,这怎么可能?

#include<stdio.h>
#include<stdlib.h>

int main()
{
    char temp[100], str[100];
    fgets(str, 100, stdin);
    int i;
    for(i = 0; str[i]!='\0'; i++)
    {
        temp[i] = str[i];
    }
    puts(temp);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c arrays string null copying

8
推荐指数
2
解决办法
1517
查看次数

如果字符串中间存在空字符怎么办?

我知道字符串的结尾由空字符表示,但我无法理解以下代码的输出.

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

int
main(void)
{
    char s[] = "Hello\0Hi";
    printf("%d %d", strlen(s), sizeof(s));
}
Run Code Online (Sandbox Code Playgroud)

输出:5 9

如果strlen()在o的末尾检测到字符串的结尾,那为什么sizeof()不做同样的事情呢?即使它没有做同样的事情,也不是'\ 0' 一个空字符(即只有一个字符),所以答案不应该是8吗?

c null sizeof strlen

3
推荐指数
4
解决办法
6125
查看次数

scanf 不能在 while 循环中工作

我试图在文件中输入一些数字,因此创建了一个 while 循环。输入值后,我询问用户是否希望重复该过程。但是,程序只打印第二个 printf 语句,while 循环终止。该计划是:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    FILE *fp;
    fp = fopen("numbers.txt", "w");
    int a;
    char ch = 'y';
    while(ch == 'y')
    {
        printf("Enter the number\n");
        scanf("%d", &a);
        fprintf(fp, "%d", a);
        printf("Do you want to continue?");
        scanf("%c", &ch);                           //doesn't work at all
    }
    fclose(fp);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么第二个 scanf 不起作用?

c file while-loop

1
推荐指数
1
解决办法
4368
查看次数

标签 统计

c ×3

null ×2

arrays ×1

copying ×1

file ×1

sizeof ×1

string ×1

strlen ×1

while-loop ×1