【问题标题】:Converting user input to an array of characters, and filtering letters from other characters?将用户输入转换为字符数组,并从其他字符中过滤字母?
【发布时间】: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 &lt;= 10; --> i = 0; input_str[i]; 2) isalpha(ch) == true --> isalpha((unsigned char)ch)
  • i &lt;= 10 应该是 i &lt; 10。数组索引从 0 到 9。

标签: c arrays user-input fgets strtol


【解决方案1】:

你有一些问题。

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

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

要获得在字母表中的位置,您可以简单地从字符的值中减去Aa 的值。使用tolower()toupper() 将字符转换为您要使用的大小写。您的方法有效,但过于复杂和令人困惑。

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

for循环中,执行赋值应该是i = 0,而不是比较的i == 0

您也不应该过多地使用全局变量。并且系统头文件周围应该有&lt;&gt;,而不是""

#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;
}

【讨论】:

  • 非常感谢您的快速回复,从中学到了很多东西......,干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 2011-09-18
  • 2013-12-01
  • 1970-01-01
相关资源
最近更新 更多