我正在使用dev c ++。这是一个愚蠢的程序,要求正确的键显示文本。这个程序与“int”类型完全一致(只是数字):
#include <stdio.h>
#include<conio.h>
main()
{
int key;
printf("This program show a mensage if you get the correct key \n");
printf("Write the key:\n");
scanf("%i",&key);
if(key==1234)
{
printf("Welcome to stackoverflow \n");
}
else
{
printf("You keep going slept \n");
}
getch();
return 0;
}
但是我怎样才能替换字符串,例如:sesame,house等。
我试过矩阵:
char key[];
然而我得到错误。
Sincerily NIN。
更新
我可以得到一个新程序:
#include <stdio.h>
#include<conio.h>
main()
{
char key[7]; /*replace int for char*/
printf("This program show a mensage if you get the correct key \n");
printf("Write the key:\n");
scanf("%c",&key);
if(key=="sesame") /*numbers for string*/
{
printf("Welcome to stackoverflow \n");
}
else
{
printf("You keep going slept \n");
}
getch();
return 0;
}
然而,即使我修正了正确的钥匙(“芝麻”),我也会得到“你继续睡觉”
答案 0 :(得分:4)
您无法使用==运算符
比较字符串的值 if(key=="sesame") // This compares pointers
你需要
if(strcmp(key,"sesame") == 0)
请参阅:http://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm
另外
scanf("%c",&key);
不起作用。 %c只有1个字符。 你需要%s代表字符串。
int ret = scanf("%6s", key); // or scanf("%6s", &key[0]);
if (ret < 0)
{
// The function returns the number of input items successfully matched and assigned,
// which can be fewer than provided for, or even zero in the event of an early matching failure.
// The value EOF is returned if the end of input is reached before either the
// first successful conversion or a matching failure occurs. EOF is also returned
// if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
// see: http://linux.die.net/man/3/scanf
}
请注意,您只需要key
或&key[0]
作为指向key
缓冲区的指针。
答案 1 :(得分:1)
问题1:
operator !=
不对。它只会读一个字符。你需要使用
scanf("%c",&key);
问题2:
scanf("%6s", key);
不是比较两个字符串的正确方法。它将比较两个指针并将评估为false。你需要使用:
if(key=="sesame")
答案 2 :(得分:-1)
#include <stdio.h>
int main()
{
char *a = "sesame";
printf("this program show a message if you get the correct key \n");
printf("write the correct key:\n");
// scanf("%c",&key);
if(a == "sesame")
{
printf("welcome to stack overflow \n");
}
else
{
printf("you keep going to sleep \n");
}
return 0;
}