Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.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
Can';t将字符放入C中的字符数组中_C_Arrays_Char_Scanf - Fatal编程技术网

Can';t将字符放入C中的字符数组中

Can';t将字符放入C中的字符数组中,c,arrays,char,scanf,C,Arrays,Char,Scanf,我想创建和操作角色数组。我不想使用字符串。 以下是我用C语言编写的代码: int main(int argc, char *argv[]) { char s[4]; int i; for(i = 0; i < 4; i++){ printf("Character at %d : ",i); scanf("%c",&s[i]); printf("%c",s[i]); } return 0; }

我想创建和操作角色数组。我不想使用字符串。 以下是我用C语言编写的代码:

int main(int argc, char *argv[]) {
    char s[4];
    int i;
    for(i = 0; i < 4; i++){
        printf("Character at %d : ",i);
        scanf("%c",&s[i]);
        printf("%c",s[i]);
    }
    return 0;
}
intmain(intargc,char*argv[]){
chars[4];
int i;
对于(i=0;i<4;i++){
printf(“在%d处的字符:,i”);
scanf(“%c”、&s[i]);
printf(“%c”,s[i]);
}
返回0;
}
当我执行它时,似乎:

  • 编译器从数组中
    i
    处的元素跳到
    i+2处的元素
  • 数组中未添加任何内容。数组保持为空

我想了解
scanf(“%c”和&s[I])有什么问题我认为是该指令导致了该代码中的问题。

它没有像您预期的那样工作,因为
scanf()
只需要一个字符,但在您按下enter键之前,它只会这样做。因此,输入字符仍在缓冲区中,将由下一次迭代的
scanf()
读取

有关如何更改代码的建议,请参阅。

scanf()
无法按预期工作
scanf()
还将按enter键视为字符。如果您坚持使用
scanf()
,这里有几个解决当前代码的方法

方法1

int main(int argc, char *argv[]) {
    char s[4];
    char enter;
    int i;
    for(i = 0; i < 4; i++) {
        printf("Character at %d : ",i);
        scanf("%c", &s[i]);
        scanf("%c", &enter);
        printf("%c \n", s[i]);
    }
    return 0;
}
int main(int argc, char *argv[]) {
    char s[4];
    int i;
    for(i = 0; i < 4; i++) {
        printf("Character at %d : ",i);
        scanf("%c", &s[i]);
    }
    for(i = 0; i < 4; i++) {
        printf("\n %c", s[i]);
    }
    return 0;
}
int main(int argc, char *argv[]) {
    char s[4];
    int i;
    for(i = 0; i < 4; i++) {
        printf("Character at %d : ",i);
        scanf(" %c", &s[i]); // Note the whitespace before %c
        printf("\n %c", s[i]);
    }
    return 0;
}