Altaïr
Altaïr

Reputation: 39

How do I keep reading from a keyboard in C while outputting results?

I want to read a string and 4 integers then display what I read then read again a string and 4 integers. I want to keep doing this until i get to the end of file ( hitting ctrl + D). For example :

tennis 4 2 3 2 (hit enter)

(the output)

helloworld 2 8 7 4 (hit enter)

(the output)

Here is what I tried to do :

#include <stdio.h>

int main() {
  char name[30];
  int won = 0;
  int lost = 0;
  int tie = 0;
  int streak = 0;
  int ch;

while((ch = getchar()) != EOF)
{
    scanf("%s %d %d %d %d",name,&won,&lost,&tie,&streak);
    printf("%s%d%d%d%d",name,won,lost,tie,streak);
}   
return 0;
}

Upvotes: 1

Views: 132

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Simple, read the documentation of scanf() and write this

while (scanf("%s%d%d%d%d", name, &won, &lost, &tie, &streak) == 5)
    printf("%s: %d %d %d %d\n", name, won, lost, tie, streak);

In your code, you are reading all the characters from stdin and then calling scanf(), so after you press enter the code will call scanf() passing all the characters after the first to it.

Also, to prevent overflow you can pass a maximum number of characters as a length modifier to the "%s" specifier, which you can also read in the manual at the link above. And finally you should take into account that the "%s" specifier will not work if the string have spaces in it.

Upvotes: 0

rootkea
rootkea

Reputation: 1484

while(scanf("%29s%d%d%d%d",name,&won,&lost,&tie,&streak) == 5)
    printf("%s%d%d%d%d",name,won,lost,tie,streak);  

From man -s3 scanf:

These functions return the number of input items successfully matched and assigned

Upvotes: 3

Related Questions