I wrote a C program that counts the number of characters in a string, but someth
ID: 665717 • Letter: I
Question
I wrote a C program that counts the number of characters in a string, but something is wrong with my getaline function. Any string the user enters returns 10 characters. Can someone provide me with a function that returns the correct value? The main function cannot be changed and the parameters for the getaline function cannot be changed.
#include
int getaline(char *s, int limit);
int main(){
int limit=10;
char str[11];
int num;
printf("Please input a string: ");
num=getaline(str,limit);
printf("String "%s" contains %d characters ", str,num);
return 0;
}
int getaline(char *s, int limit) {
int i,n=0;
for(i=0;i {
s[i]=getchar();
n++;
}
return n;
}
Explanation / Answer
Modified code which will read less than 10 character also:
#include<stdio.h>
int getaline(char *s, int limit);
int main(){
int limit=10;
char str[11];
int num;
printf("Please input a string: ");
num=getaline(str,limit);
printf("String "%s" contains %d characters ", str,num);
return 0;
}
int getaline(char *s, int limit) {
int i,n=0;
for(i=0;i<limit;i++){
char c=getchar();
if(c==' ') //check for new line
break;
else //if not new line
s[i]=c;
n++;
}
return n;
}