使用 getchar() 和 putchar() 用数组输入和输出一组字符

Input and output a set of character with an array by using getchar() and putchar()

我是 C 语言世界的新手,对函数 putchar() 和 getchar() 不是很熟悉。我尝试编写一个代码来读取一组输入的字符并将其存储在数组中。 这是我的代码:

#include<stdio.h>
#include<ctype.h>
#define MAX_SIZE 100

int main(){
    int i;
    char c[MAX_SIZE]={0};
    printf("Enter message:");

    for(i=0;getchar()!='\n';i++){
        c[i] = getchar();    /*looks like some error here that the compiler didn't found out.....*/
    }

    for(i=0;c[i]!='\n';i++){
        putchar(c[i]);
    }

    return 0;
}

程序运行成功但运行不正常。输出的结果很乱,完全没有意义。 我想知道我的代码有什么问题,因为它对我来说看起来没有错误(编译器也是如此)。我希望除了得到正确的书写方式之外还能得到解释。

改为使用以下内容

int value;

for ( i = 0; i < MAX_SIZE && ( value = getchar() ) != EOF && value != '\n'; i++ )
{
    c[i] = value;
}

for ( int j = 0; j < i; j++ )
{
    putchar( c[j] );
}

putchar( '\n' );

否则至少在这个循环中

for(i=0;getchar()!='\n';i++){
        ^^^^^^^^   

您正在跳过每个偶数字符

并且头文件 <ctype.h> 可能会被删除,因为头文件中的声明都没有在程序中使用。