Question

A very simple program is not even working.

int main ()
{
  int  n; 
  while (scanf("%d", &n) > 0)
  return 0;
}

The above I would expect to only read to input but it also prints the input:

2
2
3
3

I would have expected the above behavior if I had also this line in the while loop but I don't:

printf("%d\n", n);

Can you explain?

Update

There is nothing in the answers that explain why this is happening. And no setting in the Nios 2 IDE for local echo turned on or off. And if there were it probably would not be dafeult causing unexpected output. And this program also prints its input:

#include <stdio.h>

int main ()
{
  int  n; 
  while (scanf("%d", &n) > 0)
    ;
  return 0;
}

So this Nios 2 IDE which is based on Eclipse is nobody's choice since you cannot figure out why it is behaving in a way it shouldn't

Was it helpful?

Solution

2 candidates

  1. Your terminal I/O has an unneeded local echo turned on. Thus an OS issue, not a issue of this program.

  2. Missing ; at end of while() invokes expected results. The code as posted should simple read some input and then immediately exit. This is not as the OP recounts. Suspect it is a mis-transcription of the problem.
    [edit] Now see all of @alk solution. Certainly something is in the OP's real code that is not visible in the post -maybe due to mixed \r and \r\n and \n?

    // Was it a typo that the OP did not have a;at the end?
    while (scanf("%d", &n) > 0)

OTHER TIPS

Most probably your code looked like this:

int main ()
{
  int  n; 
  while (scanf("%d", &n) > 0)                                                                                           printf("%d\n", n);
  return 0;
}

// ------------------------------------------------------------------ scroll right >>> --------------------------------------------------

scanf() returns integer which is number of parameters given as input. In your case scanf("%d",&n) returns 1.

You can check this as ref- http://cboard.cprogramming.com/c-programming/119407-scanf-return-values.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top