检查用户是否在 C 中输入字母或数字
有没有一种简单的方法来调用 C 脚本来查看用户是否输入了英文字母表中的字母?我在想这样的事情:
if (variable == a - z) {printf("You entered a letter! You must enter a number!");} else (//do something}
我想检查以确保用户没有输入字母,而是输入了数字。想知道是否有一种简单的方法可以提取每个字母而无需手动输入字母表中的每个字母:)
Is there an easy way to call a C script to see if the user inputs a letter from the English alphabet? I'm thinking something like this:
if (variable == a - z) {printf("You entered a letter! You must enter a number!");} else (//do something}
I want to check to make sure the user does not enter a letter, but enters a number instead. Wondering if there is an easy way to pull every letter without manually typing in each letter of the alphabet :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
最好测试十进制数字本身而不是字母。 isdigit。
It's best to test for decimal numeric digits themselves instead of letters. isdigit.
isalpha() 将一次测试一个字符。如果用户输入像 23A4 这样的数字,那么您想要测试每个字母。您可以使用这个:
我同意 atoi() 不是线程安全的并且是一个已弃用的函数。您可以编写另一个简单的函数来代替它。
isalpha() will test one character at a time. If the user input a number like 23A4, then you want to test every letter. You can use this:
I agree that atoi() is not thread safe and a deprecated function. You can write another simple function in place of that.
除了 isalpha 函数之外,您还可以这样做:
Aside from the isalpha function, you can do it like this:
strto*()
库函数在这里派上用场:The
strto*()
library functions come in handy here:您还可以通过一些简单的条件来检查是否字符是否为字母
或者您也可以使用 ASCII 值
You can also do it with few simple conditions to check whether a character is alphabet or not
Or you can also use ASCII values
您可以实现以下返回布尔值的函数,它检查输入是否仅由字符而不是数字组成,它还会忽略空格。请注意,它假设输入是由 fgets 而不是 scanf 收集的。仅当您想使用其他输入法时才应更改 while 条件。
You can implement the following function that returns a boolean, it checks whether the input is only composed by characters and not numbers, it also ignores spaces. Note that it supposes that the input in collected by fgets and not scanf. You should only change the while condition if you want to use another input method.