Hello,
I'm kinda new to C++ so I need some help. I've written this program and now I need it modified to possibly do the following...
Output every 4th letter from the string or
Count the occurrences of different letters.
This is simple, basic C++ using Microsoft Visual C++ 1.52 (1993), yes i know ancient but it needs to be done this way.
Thanks in advance..
Jason K

#include <iostream.h>
#include <stdlib.h>
#include <time.h>
void main()
{
srand((unsigned)time(NULL));//Needed for random
 
char abc[]="abcdefghijklmnopqrstuvwxyz";
char user[256];
int numletters;
 
cout<<"How many letters do you want in your random string? ";
cin>>numletters;//User Input
 
for(int i=0;i<=numletters;i++)
{
if(i==numletters)//end the string
user[i]='\0';
else
user[i] = abc[rand()%26+0];//Pick a random spot in alphabet array and assign it to new string
 
}
cout<<"\n"<<user;
}

the unsigned char data type has a range of 0 to (and including) 255. So all you need is an int array of that size to count the number of occurences of all characters. Initialize the array to all 0s then use the char itself as the index into the array.

int counts[255] = {0};
char letters[]= "aabceqoiwer'pojadgojzfgoijwef";
int i;
for(i = 0; letters[i]; i++)
   counts[letters[i]]++;

now all you have to so is search the array counts[] for non-zero values and you have the counts you want.

If you were using a modern c++ compiler then there would be c++ <map> class that would work better.

the unsigned char data type has a range of 0 to (and including) 255.

The unsigned char type has exactly the range of 0 to (and including) UCHAR_MAX. UCHAR_MAX may be 255, or it may not. When in doubt, why not be exact?

David, I know you are right about that, but have you ever heard of an os where the max value is anything other than 255? There could be one, but it is probably so obscure hardly anyone uses it.

For a freestanding implementation, I have indeed worked with CHAR_BIT of 16. Imagine what this does to code with lots of these shortcuts in it.

So pretend you've written a wonderful little network stack, or something, that you make open source. I grab it and have to portablize it. This sucks. Been there, done that. So I don't encourage folks to write something that may annoy me down the road when writing it correctly the first time does not take all that much extra effort.

Everyone seems to understand backward compatibility, but they never seem to understand forward compatibility.

For a freestanding implementation, I have indeed worked with CHAR_BIT of 16. .

But I'll bet UCHAR_MAX value is still 255 (not referring to UNICODE wchar_t).

But I'll bet UCHAR_MAX value is still 255 (not referring to UNICODE wchar_t).

No, it is 65535 because it has to be.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.