I have done my school assignment, and I try to fix it by the tutor's comment. However, from my tutor latest email, he points out that "It is luck if it works without making this change. With local variables, you have no idea what is in them by default." I just have no idea what the default is in my code
This is my tutor's comment: 1. The question said only local variables should be used.
The read function was supposed to read in as well as do validation of the length of the input string. Lines 14 and 15 should be inside the read function, not in main.
Because you used text as a global variable, you have been able to write your functions without the need for the string parameters s, st and str. The whole point of this assignment was to test your ability to program with string parameters. While your functions appear to have string parameters, they might as well not be there with text global and only text in the code inside the functions. The read function should be written in terms of s, not text. The count function should be written in terms of st, not text. The justify function should be have str wherever you have text. You have not shown that you understand how string parameters are used.
#include<stdio.h>
#include<string.h>
void read(), justify(char *str, int g);
int count(char *st);
int main(){
char text[100];
int gaps, i;
gaps = 0;
for(i=0; i<3; i++) {
read(text);
gaps = count(text);
justify(text, gaps);
printf("\n");
}
}
void read(char *s){
int length;
printf("Enter a line of text: ");
gets(s);
length = strlen(s);
while(length!=0){
if(length<46){
printf("123456789012345678901234567890123456789012345\n");
length = 0;
} else {
printf("Enter a line of text: ");
gets(s);
length = strlen(s);
}
}
}
int count(char *st){
int num, i, num2;
num = 0;
num2 = strlen(st);
for(i=0; i<num2; i++){
if(st[i]==' '){
num++;
}
}
return num;
}
void justify(char *str, int g){
int i, j, num, m, n, temp;
temp = strlen(str);
num = 45 - temp;
m = num / g;
n = num % g;
for(i=0; i<temp; i++){
printf("%c", str[i]);
if(str[i]==' '){
for(j=0; j<m; j++){
printf(" ");
}
if(n!=0){
printf(" ");
n--;
}
}
}
printf("\n");
}
I would like to learn how to improve the code and make it work without luck. Cheers!