我的代码不起作用,我也不知道为什么;-;

问题描述 投票:-2回答:1

我刚刚看完有关C编程的视频,我想做一个像我的世界一样的坐标系,我所要做的就是如果我按下一个键,它会使Y值更高,等等,也很抱歉我的语法不是最好的

#include <stdio.h>

int main () {
int x = 0;
int y = 0;
int z = 0;
char input;
scanf("%s", input);
if(input == 'w') {
    printf("test");
    y++;
}
}

编译器日志

gcc -Wall -o "move" "move.c" (in directory: /home/nonetrix/Desktop)
move.c: In function ‘main’:
move.c:8:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
    8 | scanf("%s", input);
      |        ~^   ~~~~~
      |         |   |
      |         |   int
      |         char *
move.c:6:5: warning: unused variable ‘z’ [-Wunused-variable]
    6 | int z = 0;
      |     ^
move.c:4:5: warning: unused variable ‘x’ [-Wunused-variable]
    4 | int x = 0;
      |     ^
move.c:8:1: warning: ‘input’ is used uninitialized in this function [-Wuninitialized]
    8 | scanf("%s", input);
      | ^~~~~~~~~~~~~~~~~~
Compilation finished successfully.

它说它已编译,但是当您尝试运行它时会得到

w
Segmentation fault (core dumped)


------------------
(program exited with code: 139)
Press return to continue



c segmentation-fault compiler-warnings
1个回答
-1
投票

您应该使用getcharfgetc仅读取一个字符。具有scanf格式的%s用于读取整个字符串。

请注意,这不会是“响应式”,您将始终需要按回车键

© www.soinside.com 2019 - 2024. All rights reserved.