Input/Output for lines of text: Difference between revisions

m
(Haskell - Update to read N lines)
Line 180:
}
</lang>
 
Alternative code:
 
This program will read a number through STDIN... well, trough pipeline:
 
$ echo n | io
 
where "n" is the number of lines it will print.
 
When the total number of lines entered has been reached, it will display a message indicating that you must enter a number.
 
<lang C>
// Programa IO.C
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
 
int check_number(const char *s){
const char*t=s;
while(*t!='\n'){
if( !isdigit(*t) ) return 0;
++t;
}
return 1;
}
int main( int argc, char *argv[] )
{
char s[100],r[10];
int n=0;
FILE *fp;
fgets(s,100,stdin); // input trough stdin.
if( (fp = fopen("temporal.txt","r"))!=NULL){
fgets(r,10,fp);
n=atoi(r);
if(n>0){
--n;
fclose(fp);
fp=fopen("temporal.txt","w");
sprintf(r,"%d",n);
fputs(r,fp);
fclose(fp);
printf("%d, %s\n",n,s);
}else{
fclose(fp);
remove("temporal.txt");
perror("I need a number of the lines here!\n");
}
}else{
if(check_number((const char*)s)){
fp=fopen("temporal.txt","w");
fputs(s,fp);
fclose(fp);
}else{
perror("I need a number of the lines here!\n");
}
}
return 0;
}
</lang>
{{out}}
<pre>
$ echo 3 | ./io
$ echo "hola" | ./io
hola
 
$ echo "hola mundo" | ./io
hola mundo
 
$ echo "lore ipsum et la concha de la lora latinus" | ./io
lore ipsum et la concha de la lora latinus
 
$ echo "lore ipsum et la concha de la lora latinus" | ./io
I need a number of the lines here!
: Success
$
</pre>
 
=={{header|C++}}==
545

edits