Help Counting Characters function
Hello All;
I'm doing an exercise that prints all input lines that are longer than 80 characters. I rather not use any libraries so I decided to write my own function that counts characters to use it in my main program. However when integrate things my function returns zero all the time. Not sure where I'm going wrong with this.
Here is my full code:
Code:
/*
Exercise 1-17 Write a program to print all input lines that
are longer than 80 characters
*/
#include<stdio.h>
/* Declarations*/
#define MAX_STRING_LEN 1000
int count_characters(char S1[]);
int main() {
char S1[MAX_STRING_LEN];
int length;
int m = 80;
/* Ask user for a string */
printf("Input a string:\t");
scanf("%s", S1);
/* obtain the length of the string*/
length = count_characters(S1);
/* print if the string length is over the value of "m" otherwise say why not */
if (length > m)
printf("String length is %d\nOriginal String input is: %s\n", length, S1);
else
printf("String length is %d\nWill not print because is equal or less than %d\n", length, m);
}
/* counts the characters in a string */
int count_characters(char s[])
{
int nc =0;
int c;
for (nc = 0; (c = getchar()) != '\n'; ++nc);
return nc;
}
so I was trying to debug my count_characters() function and this is the code if I was to run it seperately:
Code:
#include <stdio.h>
/* counts character of a string*/
main()
{
int nc = 0;
int c;
for (nc = 0; (c = getchar()) != '\n'; ++nc);
printf("Number of characters = %d\n", nc);
}
which works, so I'm a little confused, could anyone give me a hint on what I'm doing wrong?
Thanks
note: I'm trying to learn C and so far I'm in chapter 1&2 of the "C programming Language" by Dennis M. Ritchie