【发布时间】:2016-10-26 22:12:54
【问题描述】:
我习惯了 java,尽管知道理论,但我仍然在努力学习 C++ 的基本语法。我有一个函数试图计算字符串中出现的次数,但输出有点奇怪。
这是我的代码:
#include <cstdlib>
#include <iostream>
#include <cstring>
/*
main
* Start
* prompt user to enter string
* call function
* stop
*
* count
* start
* loop chars
* count charts
* print result
* stop
*/
using namespace std;
void count(const char s[], int counts[]);
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
这是输出:
输入一个字符串:Dylan
你进入了迪伦
b:1次
c:1次
d:2次
f:1次
小时:1次
我:1229148993次
j:73次
l: 2 次p>
n:2次
p:1次
r:1次
v:1次
您能给我的任何帮助将不胜感激。尽管这是简单的东西,但我是一个 java 傻瓜。 -_-
【问题讨论】:
-
int counts[26] = {0}; -
初始化
counts。目前你不知道内存中有什么,而且通常 C++ 不会为你初始化存储,因为你相信如果你关心值是什么,你就会设置它。int counts[26] = {0}; -
int map[121];你可以这样做。如果你是字母表都是 7 位字符
-
确实,这是与 Java 的区别之一。那里一切都被初始化,默认为
0。 -
@self:对,因为 2^7 是 121...
标签: c++ arrays string function for-loop