Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用getchar()和putchar()输入和输出一组带有数组的字符_C_Arrays_For Loop_Character_Getchar - Fatal编程技术网

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

使用getchar()和putchar()输入和输出一组带有数组的字符,c,arrays,for-loop,character,getchar,C,Arrays,For Loop,Character,Getchar,我是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()!='

我是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;
}
#包括
#包括
#定义最大尺寸100
int main(){
int i;
字符c[MAX_SIZE]={0};
printf(“输入消息:”);
对于(i=0;getchar()!='\n';i++){
c[i]=getchar();/*这里看起来像是编译器没有发现的某个错误*/
}
对于(i=0;c[i]!='\n';i++){
putchar(c[i]);
}
返回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' );
您正在跳过每个偶数字符


而且头
可能会被删除,因为程序中没有使用头中的声明。

这是否意味着getchar()每次都会读取下一个字符,无论我在哪里使用?这是写它的唯一方法吗?@grasshelper是的,如果你甚至不指定它的结果,getchar将读取下一个字符。
for(i=0;getchar()!='\n';i++){
        ^^^^^^^^