【发布时间】:2019-01-03 17:46:19
【问题描述】:
我用 C++ 编写了一个程序,它应该打印某个字母包含在一个单词中的次数。所以我使用了一个对我来说有点新的二维数组,我得到了 3 个我不太明白的错误代码。感谢您的帮助!
#include <iostream>
#include <cstring>
void check(char wArr[], int letter[], char search[], std::string word);
int main(int argc, char const *argv[]) {
//int letter[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
char search[26][2] = {{'a', 0},{'b', 0},{'c', 0},{'d', 0},{'e', 0},{'f', 0},{'g', 0},{'h', 0} ,{'i', 0} ,
{'j', 0},{'k', 0},{'l', 0},{'m',0} ,{'n',0} ,{'o',0},{'p',0},{'q',0},{'r',0},{'s',0},{'t',0},
{'u', 0},{'v', 0} ,{'w',0},{'x',0},{'y', 0},{'z', 0}};
std::string word;
std::cout << "Please enter the word: \n";
std::cin >> word;
char wArr[word.length()];
strcpy (wArr, word.c_str ());
check(wArr, search, word);
return 0;
}
void check(char wArr, char search[][2], std::string word){
for(int s = 0; s < 26; s++) {
for ( char i = 0; i < word.length(); i++) {
if(wArr[i] == search[s][1]) {
search[s][2]++;
}
}
}
for (int t = 0; t < 26; t++) {
if(search[t][2] > 0){
std::cout << search[t][1] << ": " << search[t][2] << '\n';
}
}
}
错误代码:
/home/julian/workspace-atom/countletter/main.cpp: In function ‘int main(int, const char**)’:
/home/julian/workspace-atom/countletter/main.cpp:16:33: error: cannot convert ‘char (*)[2]’ to ‘int*’ for argument ‘2’ to ‘void check(char*, int*, char*, std::__cxx11::string)’
check(wArr, search, word);
^
/home/julian/workspace-atom/countletter/main.cpp: In function ‘void check(char, char (*)[2], std::__cxx11::string)’:
/home/julian/workspace-atom/countletter/main.cpp:24:34: error: invalid types ‘char[char]’ for array subscript
if(wArr[i] == search[s][1]) {
^
【问题讨论】:
-
您的具体问题是?如果你问我,错误很清楚。
-
初学者看
check的声明和定义。 -
这个
char wArr[word.length()];不是有效的 C++。您的代码比错误消息更难理解。
标签: c++ arrays sorting multidimensional-array