我知道您可以使用 scanf 并获取要在 if 子句中使用的字符,但是,有没有办法使用字符串来执行此操作?
例如
printf("enter 'foo' to do 'bar', otherwise enter 'hay' to do 'wire');
scanf("%string", &stringNAME); //this is the part where I have no idea what to do
if (stringNAME == 'foo'){do bar} //here, issues occur with multicharacter character :/
if (stringNAME == 'hay'){do wire}
最佳答案
您已经差不多完成了,只需进行一些调整。
char stringNAME[10];
printf("enter 'foo' to do 'bar', otherwise enter 'hay' to do 'wire');
scanf("%9s", stringNAME);
if (!strcmp(stringNAME,"foo"){do bar}
if (!strcmp(stringNAME,"hay")){do wire}
注意 scanf 中的数字 9。它应该比输入字符串的大小少(或小)1。否则,您将面临缓冲区溢出的风险,这是一件令人讨厌的事情。 fgets
是一个更好的选择,因为您被迫限制字符数。这就是您要执行的操作(只需替换 scanf
行)
fgets(stringNAME, 10, stdin)
关于c - 使用 scanf 获取字符串,然后对该字符串使用 if 语句,而不是 c 语言中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13811312/