Originally Posted by
Acer
I am trying to get the programme to firstly print the ascii values of the first ten chars in the array s. I am also trying to build a function that counts the number of 4 letter words typed into it.
Any help would be hugely appreciated, thanks!
Code:
#include <stdio.h>
main()
{
void show( const char s[]);
int mylen( const char * s);
char buff[100];
while (scanf(" %s", buff) != EOF){
// Hold a zero terminated string
}
}
Counting can be done like this:
Code:
char* buffer = "Hello World";
int i;
for (i = 0 ; i < 10 && i < strlen(buffer) ; ++i)
{
printf("Letter %c in ASCII is %d\n", buffer[i], buffer[i]);
}
A integer and a character are basically the same thing, except since a character is simply 1 byte (typically), it can only count up to 255, while an integer is 4 bytes (typically). It's all how you choose to display the information (notice the variable formatting in the printf() function, the first one specifies that it be print out as a char, as one would expect, but the %d specifies that it be printed out as a decimal, which is its ASCII value.
As for counting the number of 4 letter words, use a string tokenizer, a fairly common tool for parsing strings.
Code:
int count = 0;
char* buffer = "These are some words, not all of them are four letters"
char* token = strtok(buffer, " \t");
while (token)
{
if (strlen(token) == 4)
count++;
token = strtok(NULL, " \t");
}
A tokenizer takes a string (char buffer), and a string of characters representing delimiters (separators). Subsequent calls to the tokenizer take a NULL pointer as the first parameter which tells it to continue where it left off last time. The tokenizer will return a NULL pointer when there are no more tokens left.
A token is just a "word" so to speak - that is, anything in between the delimiters, in the case above, I set the delimiters to spaces and tabs (general whitespace) with the string " \t".
Hope that helps ya out some.
God I hope that's not homework...
Feel free to PM me if you have any more specific questions, sometimes I don't see responses to my posts.