【发布时间】:2017-05-26 20:50:49
【问题描述】:
#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' or 'A' = 1, 'b' or 'B' = 2..etc)。我一直在搜索 stackoverflow 上的其他一些帖子,这帮助我走到了这一步(使用 fgets 和 strtol 函数)。运行此代码时,我没有明显的语法错误,但在我输入一串字符(例如:567gh3fr)后,程序崩溃了。
基本上,我正在尝试使用“fgets”将输入的每个字符带入具有适当索引的字符串中。一旦我有了那个字符串,我就会检查每个索引是否有一个字母,如果是,我会打印分配给该字母的数字。
非常感谢任何帮助或洞察为什么这不能按预期工作,谢谢!
【问题讨论】:
-
1)
i == 0; i <= 10;-->i = 0; input_str[i];2)isalpha(ch) == true-->isalpha((unsigned char)ch) -
i <= 10应该是i < 10。数组索引从 0 到 9。
标签: c arrays user-input fgets strtol