如何将用户输入存储为 c 中的变量?
How do you store user input as a variable in c?
我是一个非常新手的程序员,对自己在做什么一无所知。除了阅读文档。
我的程序没有给用户时间来立即输入无线,它只是说不。我做错了什么?
我让这个程序成为朋友们的笑话(就像 AI 出了问题)
这是我的代码:
#include <stdio.h>
int main() {
int yorn;
printf("do you have friends? please awnser yes or no.");
scanf("%d", &yorn );
if (yorn = "yes") {
printf("no, you dont. please reload the program if you want to change your awnser.");
}
else if (yorn = "no") {
printf("i can be your friend. your BEST friend.");
}
return 0;
}
为了比较,你有两个使用 strcmp
而不是 =
。此外,您正在为 yorn
使用 int
类型并与字符串进行比较。将纱线类型更改为 char[]
并在 scanf
.
中读取为 %s
将代码更改为遵循代码。仔细看就明白了:
int main() {
char yorn[20]; //set max size according to your need
printf("do you have friends? please awnser yes or no.");
scanf("%19s", yorn); // Use %s here to read string.
if (strcmp(yorn, "yes") == 0) { //Use ==
printf("no, you dont. please reload the program if you want to change your awnser.");
}
else if (strcmp(yorn,"no") == 0) { // Use ==
printf("i can be your friend. your BEST friend.");
}
return 0;
}
我是一个非常新手的程序员,对自己在做什么一无所知。除了阅读文档。
我的程序没有给用户时间来立即输入无线,它只是说不。我做错了什么?
我让这个程序成为朋友们的笑话(就像 AI 出了问题)
这是我的代码:
#include <stdio.h>
int main() {
int yorn;
printf("do you have friends? please awnser yes or no.");
scanf("%d", &yorn );
if (yorn = "yes") {
printf("no, you dont. please reload the program if you want to change your awnser.");
}
else if (yorn = "no") {
printf("i can be your friend. your BEST friend.");
}
return 0;
}
为了比较,你有两个使用 strcmp
而不是 =
。此外,您正在为 yorn
使用 int
类型并与字符串进行比较。将纱线类型更改为 char[]
并在 scanf
.
%s
将代码更改为遵循代码。仔细看就明白了:
int main() {
char yorn[20]; //set max size according to your need
printf("do you have friends? please awnser yes or no.");
scanf("%19s", yorn); // Use %s here to read string.
if (strcmp(yorn, "yes") == 0) { //Use ==
printf("no, you dont. please reload the program if you want to change your awnser.");
}
else if (strcmp(yorn,"no") == 0) { // Use ==
printf("i can be your friend. your BEST friend.");
}
return 0;
}