简体   繁体   中英

Read an integer from stdin (in C)

I want to write a C program that takes as input an integer, and outputs its square. Here is what I have tried.

However,

  • ./a.out < 3 outputs 32768, and
  • ./a.out < 4 also outputs 32768.

Where am I wrong? Thanks.

#include <stdio.h>

int main(){
  int myInt;
  scanf("%d", &myInt);
  printf("%d\n",myInt*myInt);
}

It looks like what you're trying to do is

echo 4 | ./a.out

the syntax for < is

program < input_file

whereas | is

command_with_output | program

On the right hand side of "<", there should be a file containing the input.

try this thing:

$ echo "3" > foo
$ ./a.out < foo

Read this for more information (Specially section 5.1.2.2): http://www.tldp.org/LDP/intro-linux/html/chap_05.html

./a.out < 4

This tries to read the file named 4 and use it's content as input to a.out You can do it whichever way, but understand the < operator isn't for inputting the character you type quite literally.

One way to do this would be:

echo "4" > 4
./a.out < 4

I just run your program and its works great. If you want the program receive an integer input you should use argc , argv as folowed and not use scanf.

*The code for argc argv: *

#include <stdio.h>
#include <stdlib.h>

int main(int argc , char** argv)
{
  int myInt;
    myInt = atoi(argv[1]);
  printf("%d\n",myInt*myInt);
}

atoi - convert char* to integer.

If you want to run the program and then insert an integer, you did it right! you can read about atoi

To run this program you should comile and run from terminal:

gcc a.c -o a    
./a 3

and you will receive:

9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM