【问题标题】:Input and output a set of character with an array by using getchar() and putchar()使用 getchar() 和 putchar() 输入和输出带有数组的一组字符
【发布时间】:2019-11-06 09:24:41
【问题描述】:

我是 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;
}

程序运行成功,但运行不佳。输出的结果是混乱的,完全没有意义。 我想知道我的代码有什么问题,因为它看起来对我来说没有错误(编译器也认为它正确)。我希望我能得到一个解释,除了得到一个正确的写法。

【问题讨论】:

    标签: c arrays for-loop character getchar


    【解决方案1】:

    改为使用以下

    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++){
            ^^^^^^^^   
    

    你正在跳过每个偶数字符

    并且标题&lt;ctype.h&gt; 可能会被删除,因为程序中没有使用来自标题的声明。

    【讨论】:

    • 那么这是否意味着无论我在哪里使用 getchar() 都会读取下一个字符?这是唯一的写法吗?
    • @Grasshelicopter 是的,如果您甚至不分配结果,getchar 将读取下一个字符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多