c - 使用 scanf 获取字符串,然后对该字符串使用 if 语句,而不是 c 语言中的字符

标签 c string if-statement scanf

我知道您可以使用 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/

相关文章:

c - 将 Java NIO Files.walkFileTree 访问者移植到 C,维护线程安全

c# - 将一组三个字符串与另一个字符串进行比较

python - 当读取具有某些字符的某些数据时, string.count() 会大幅减慢

php - 警告 : filesize function failing to operate

c - C中的无限循环,有什么问题吗?

c - 制作 : flex: Command not found

c - 两个正数相乘在 C 中返回负数

c - 获得保证具有完整(4 位)年份数字的 LOCALE_SSHORTDATE 的正确方法是什么?

c - 删除字符串中所有出现的子字符串

MYSQL Inner Join if 语句