关于#c语言#的问题:最近在学习字符串的时候,练习了下提取字符串的操作

最近在学习字符串的时候,练习了下提取字符串的操作。没有语法上的问题,麻烦大家看看哪里出错了。

include
#include
#include
void Getstring(char str[], char  dstr[], int start, int stop)
{
    int i = start, j = 0;
    for (; i < stop; i++)
    {
        for (; j < i; j++)
        {
            dstr[j] = str[i];
        }
    }
    dstr[j] = '\0';
}
int main() {
    char sfz[18];
    char bd[8];
    gets(sfz);
    Getstring(sfz, bd, 6, 14);
    puts(bd);
    return 0;
}

在 C 语言中,#include 的指令需要小写,应该写作 #include<stdio.h>,其他的头文件同理。

代码使用了 gets 函数,但是在 C 语言中,gets 函数存在缓冲区溢出的问题,不安全,建议使用 fgets 函数代替。

Getstring 函数中的循环条件有误,每次都重新从 0 开始,导致 dstr 字符串的赋值不正确。

在赋值字符的过程中,缺少对索引的更新,导致只有最后一次循环中的字符被保存,其他字符被覆盖。

纠正后的代码如下:

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

void Getstring(char str[], char  dstr[], int start, int stop)
{
    int i = start, j = 0;
    for (; i < stop; i++, j++)
    {
        dstr[j] = str[i];
    }
    dstr[j] = '\0';
}

int main() {
    char sfz[18];
    char bd[8];
    fgets(sfz, sizeof(sfz), stdin);
    Getstring(sfz, bd, 6, 14);
    puts(bd);
    return 0;
}