【问题标题】:Add to array index according to each letter of user input根据用户输入的每个字母添加到数组索引
【发布时间】:2017-03-09 05:25:11
【问题描述】:

所以我正在尝试创建一个尽可能短的函数:

  1. 以字符串形式获取用户输入并将其放入 const char 数组中。
  2. 使用 for 循环获取整个 const char 数组在 for 循环中当前索引的字母位置。
  3. 然后使用字母顺序作为索引,并在 26 个整数数组中的该索引上加一。

简而言之:它记录字符串中字符的频率并将其添加到整数数组中,因此如果我输入“ABC”,它将输出 1、1、1、0、0 等,或者如果我输入 "XXYZZ" 会输出 ...0, 0, 0, 2, 1, 2。

我已经对此进行了尝试,但它似乎不起作用;

void addCommonToArray(int alphabet_common[], string userinput) {

const char * alphabet = userinput.c_str(); // String to array
int index;

for (int i = 1; i == sizeof(alphabet); i++) {
    index = alphabet[i] - 64; // Get current index and minus 64 from ascii code to get alphabetical order
    alphabet_common[index]++; // Add one to the position of the current index in the alphabet
} }

我已经对此进行了多次修改,但似乎没有出现问题,但 alphabet_common 数组是空白的。 (同样在main.cpp中有一个26个整数的数组,但是数组的所有元素都是0)所以这里的问题是数组停留在0。

感谢您的帮助!

【问题讨论】:

  • sizeof(alphabet) 会给你什么?您不应该遍历 userinput.length() 吗?为什么 i == sizeof(alphabet)?
  • @Nik 这样 for 循环就知道在哪里停止,在这种情况下,一旦 i 等于数组的大小。 sizeof(alphabet) 告诉我数组中有多少元素。
  • 你会进入for循环吗? sizeof(alphabet) 会给你什么?
  • 这就是为什么你的问题是-3 :)
  • 你自己在你的回答中承认“显然 for 循环甚至没有执行,但上面的方法似乎有效。”

标签: c++ arrays string sorting


【解决方案1】:

我修好了,

void addCommonToArray(int alphabet_common[], string userinput) {
int index;
for (char& c : userinput) {
    index = toupper(c) - 64;
    alphabet_common[index]++;
} }

显然 for 循环甚至没有执行,但上面的方法似乎有效。

【讨论】:

  • 你来这里的目的是什么?你怎么会在这里问这样的问题?
  • 详细?这里不欢迎初学者吗?哦,耻辱。
猜你喜欢
  • 2021-02-16
  • 2021-04-17
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
相关资源
最近更新 更多