为什么函数不 return 换行带有可替换关键字?

Why the functions doesn't return new line with replaceable keywords?

嘿,我只是在用 c 做一些练习,有人说 将输入字符串中的制表符替换为任何其他字符 ,我限制自己只使用 getchar(),没有 gets() fgets() 等...,因为我的学习书还没有抓住它,所以我尽量不中断流程,下面的代码只是 printf() 它收到的同一行,你能检查一下吗为什么?

#include <stdio.h>



int main(){

        char line[20];
        char c;
        int i = 0;
        printf("Enter name: ");
        while ( c != '\n'){
                c = getchar();
                line[i] = c;
                ++i;}
        while (line[i] != '[=11=]')
                if (line[i] == '\t')
                        line[i] = '*';

        printf("Line is %s \n", line);

        return 0;} 

 
  • c,用于c != '\n',一开始并没有初始化。它的初始值是不确定的,使用 is value without initializng invokes undefined behavior.
  • 您正在检查 line[i] != '[=13=]',但您从未将 '[=14=]' 分配给 line,除非从流中读取 '[=14=]'
  • 您应该在第二次循环之前初始化 i 并在第二次循环期间更新 i
  • Return getchar() 的值应分配给 int 以区分 EOF 和有效字符。
  • 您应该执行索引检查,以免导致缓冲区溢出。

固定码:

#include <stdio.h>

#define BUFFER_SIZE 20

int main(){

        char line[BUFFER_SIZE];
        int c = 0;
        int i = 0;
        printf("Enter name: ");
        while ( i + 1 < BUFFER_SIZE && c != '\n'){
                c = getchar();
                if (c == EOF) break;
                line[i] = c;
                ++i;
        }
        line[i] = '[=10=]';
        i = 0;
        while (line[i] != '[=10=]'){
                if (line[i] == '\t')
                        line[i] = '*';
                ++i;
        }

        printf("Line is %s \n", line);

        return 0;
}