I'm just start to learn C and I came across with an exercise to count the number of new lines(\n), blank spaces and tabs(\t) in stdin.
The question is,
Why:
#include <stdio.h>
int main(void){
int c, nl, ns, nt = 0;
while ((c = getchar()) != EOF) {
if (c == '\n') {
++nl;
}
else if (c == '\t') {
++nt;
}
else if (c == ' ') {
++ns;
}
}
printf("Lines: %d, Tabs: %d, Spaces: %d", nl, nt, ns);
return 0;
}
Gives me different huge and wrongs numbers based on how I provide data to program?
Using ./a.out
and typing "a" in terminal, followed by Ctrl + D:
Lines: -621574383, Tabs: 0, Spaces: 32765
Using cat input.txt | ./a.out
, with input.txt containing "a" and nothing more:
Lines: -115774576, Tabs: 0, Spaces: 32765
Using ./a.out <<< echo 'a'
:
Lines: 1775654849, Tabs: 0, Spaces: 32767
VSCode Debugger also shows huge numbers even after assign 0 to the variables.
Obs:
The declaration:
int c, nl, ns, nt = 0;
Only initializes nt
. To initialize nl
and ns
as well, you need:
int c, nl = 0, ns = 0, nt = 0;