I'm trying to initialize arrays by passing them to an initialization function as a pointer. My program compiles with no errors, but when I run it; it prints out Character Count and stops.
This is what I have so far:
#include<iostream>
#include<cctype>
#include<string>
#include<iomanip>
using namespace std;
void initialize(int *array, int n, int value);
int main()
{
char ch;
int punctuation, whitespace, digit[10], alpha[26];
punctuation = 0, whitespace = 0;
initialize(digit, sizeof(digit)/sizeof(int), 0);
initialize(alpha, sizeof(alpha)/sizeof(int), 0);
while(cin.get(ch))
{
if(ispunct(ch))
++punctuation;
else if(isspace(ch))
++whitespace;
else if(isdigit(ch))
++digit[ch - '0'];
else if(isalpha(ch))
{
ch = toupper(ch);
++alpha[ch - 'A'];
}
if(whitespace > 0)
{
cout << "Whitespace = " << whitespace << endl;
}
if(punctuation > 0)
{
cout << "Punctuation = " << punctuation << endl;
}
cout << setfill('-') << setw(17) << '-' << setfill(' ') << endl;
cout << " Character " << " Count " << endl;
cout << setfill('-') << setw(17) << '-' << setfill(' ') << endl;
return 0;
}
}
void initialize(int *array, int n, int value)
{
int i;
for (i = 0; i < n; ++i)
{
value += array[i];
}
}
I'm not sure that I am doing anything wrong here. Although, I am a bit confused as to how pointers work after they have been passed to another function. Can someone explain?
Thank you
-
In the initialize function, print the value of n.MikeC– MikeC2016年04月09日 04:19:46 +00:00Commented Apr 9, 2016 at 4:19
-
"Stops"? Hangs? Crashes? Just exits?hyde– hyde2016年04月09日 05:17:14 +00:00Commented Apr 9, 2016 at 5:17
-
It prints Character Count then exitsAmbrus– Ambrus2016年04月10日 02:21:04 +00:00Commented Apr 10, 2016 at 2:21
2 Answers 2
You probably want
a)
void initialize(int *array, int n, int value)
{
int i;
for (i = 0; i < n; ++i)
{
// no: value += array[i]; but:
array[i] = value;
}
}
see also std::fill
and b) move the return 0; off the while-loop-body
cout << " Character " << " Count " << endl;
cout << setfill('-') << setw(17) << '-' << setfill(' ') << endl;
}
return 0;
}
edit: regarding a)
You can use
std::fill(std::begin(digit), std::end(digit), 0);
std::fill(std::begin(alpha), std::end(alpha), 0);
instead of your initialize() function or (given the context) just
int punctuation, whitespace, digit[10]={0}, alpha[26]={0};
1 Comment
If you are developing in C++, why not use vectors instead? (Working with arrays* is very C style).
vector<int> array(n, value);
n = number of integers. value = value to place in each array cell.