An easy exercise to get in touch with C char and strings handling
Write
void show( const char s[])
which prints the ascii values of the first ten chars in s.
Write a function
int mylen( const char * s)
which returns the useful length of the string s. C strings are terminated by a zero char.
Please do not use strlen from the string.h library, but write it with raw C. [1]
Test this with several examples, including the null string "".
Use your function as part of a program to count the number of 4 letter words typed to it. The central part is
char buff[100];
while (scanf(" %s", buff) != EOF){
// do something with buff, which should hold
// a zero-terminated string.
}
a.out expects you to type words to it, followed by an end of file (CTRL-D).
Try
cat /usr/dict/words | a.out
SOLUTION
#include <stdio.h>
void show(const char s[]){
int i = 0;
while(i<10){
printf("%d\n",s[i]);
i++;
}
}
int mylen( const char * s){
int cont = 0;
while(s[cont]!='\0'){
cont++;
}
return cont;
}
int countFourLettersWords(){
char buff[100];
int cont = 0;
while(scanf("%s",buff)!= EOF){
if(mylen(buff)==4)
cont++;
}
return cont;
}
int main(){
char s[]="Hello world";
char empty[]="";
char num[]="01234";
show(s);
printf("Length:\n %d\n",mylen(s));
show(empty);
printf("Length:\n %d\n",mylen(empty));
show(num);
printf("Length:\n %d\n",mylen(num));
printf("I will count the four letters words:\n");
printf("%d \n",countFourLettersWords());
getchar();
}
Exercise from: CS3008
No comments:
Post a Comment