Read an integer from stdin (in C)

会有一股神秘感。 提交于 2019-12-12 03:04:33

问题


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);
}

回答1:


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



回答2:


./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



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/39936299/read-an-integer-from-stdin-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!