c - 将用户输入转换为字符数组,并过滤其他字符的字母?


#include "stdafx.h"
#include "stdlib.h"
#include <ctype.h>
int num = 0;
int i = 0;
int ch = 0;
int letter_index_in_alphabet(int ch) {
if (isalpha(ch) == true) {
char temp_str[2] = { ch };
num = strtol(temp_str, NULL, 36) - 9;
printf("%d is a letter, with %d as its location in the alphabet!", ch, num);
}
else {
return -1;
}
}
int main()
{
char input_str[10];
printf("Please enter a series of up to 10 letters and numbers: n");
fgets(input_str, 10, stdin);
for (i == 0; i <= 10; i++) {
ch = input_str[i];
letter_index_in_alphabet(ch);
}
return 0;
}

大家好,这是我在SOF上的第一篇文章!该程序的目标是从 EOF 的标准输入中读取字符。对于每个字符,报告它是否是一个字母。如果是字母,请在字母表中打印出其各自的索引("a"或"A"= 1,"b"或"B"= 2..etc)。我一直在搜索堆栈溢出的其他一些帖子,这帮助我走到了这一步(使用 fgets 和 strtol 函数)。运行此代码时我没有明显的语法错误,但是在输入字符串(例如:567gh3fr)后,程序崩溃。

基本上,我尝试使用"fgets"将输入的每个字符放入具有适当索引的字符串中。一旦我有了那个字符串,我就会检查每个索引中是否有一个字母,如果是,我打印分配给字母表中该字母的数字。

非常感谢任何帮助或见解,以说明为什么这没有按预期工作,谢谢!

你有几个问题。

首先,char input_str[10]只够用户输入 9 个字符,而不是 10 个字符,因为您需要允许一个字符用于结束字符串的空字节。

其次,你的循环走得太远了。对于包含 10 个字符的字符串,索引最多为 9,而不是 10。当它到达空字节时,它也应该停止,因为用户可能没有输入所有 9 个字符。

要获得字母表中的位置,您只需从字符的值中减去Aa的值。使用tolower()toupper()将字符转换为要使用的大小写。您的方法有效,但它过于复杂和混乱。

letter_index_in_alphabet()声明返回int。但是当字符是字母时,它不会执行return语句。我不确定为什么它应该返回一些东西,因为你从不使用返回值,但我已将其更改为返回位置(也许调用者应该是打印消息的人,所以函数只是进行计算)。

for循环中,应该i = 0执行分配,而不是i == 0比较。

你也不应该过多地使用全局变量。系统头文件周围应该有<>,而不是"".

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int letter_index_in_alphabet(int ch) {
if (isalpha(ch)) {
int num = tolower(ch) - 'a' + 1;
printf("%d is a letter, with %d as its location in the alphabet!n", ch, num);
return num;
} else {
return -1;
}
}
int main()
{
char input_str[10];
printf("Please enter a series of up to 9 letters and numbers: n");
fgets(input_str, sizeof(input_str), stdin);
for (int i = 0; input_str[i]; i++) {
letter_index_in_alphabet(input_str[i]);
}
return 0;
}

相关内容

最新更新