therefore, I am just looking at the basic k & r exercises. Exercise: Exercise 1-8. Write a program to count spaces, tabs, and newlines.
I tried to create a structure with elements of spaces, tabs and newlines. I also encoded the init function to set these members to 0.
Now I will show you the source code and output.
#include <stdio.h>
typedef struct Counter Counter;
struct Counter
{
int blanks;
int tabs;
int newlines;
};
void initCounter(Counter arg)
{
arg.blanks = 0;
arg.tabs = 0;
arg.newlines = 0;
};
int main()
{
int c;
Counter cnt;
initCounter(cnt);
while((c = getchar()) != EOF)
{
if(c == ' ')
{
++cnt.blanks;
}
if(c == '\t')
{
++cnt.tabs;
}
if(c == '\n')
{
++cnt.newlines;
}
}
printf("\nBlanks: %d", cnt.blanks);
printf("\nTabs: %d", cnt.tabs);
printf("\nNewlines: %d\n", cnt.newlines);
return 0;
}
This is the conclusion:
give it another try boom
Blanks: -416565517
Tabs: 32768
Newlines: 1
Any advice what went wrong? Thanks and best regards.
source
share