简体   繁体   English

从stdin读取一个整数(在C中)

[英]Read an integer from stdin (in C)

I want to write a C program that takes as input an integer, and outputs its square. 我想编写一个C程序,将一个整数作为输入,并输出其平方。 Here is what I have tried. 这是我尝试过的。

However, 然而,

  • ./a.out < 3 outputs 32768, and ./a.out < 3输出32768,和
  • ./a.out < 4 also outputs 32768. ./a.out < 4也会输出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 $ echo“ 3”> foo
$ ./a.out < 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 请阅读以获取更多信息(特别是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. 这会尝试读取名为4的文件并将其内容用作a.out输入。您可以使用任何一种方式进行操作,但是要理解<运算符并不是要输入您真正输入的字符。

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. 如果希望程序接收整数输入,则应使用argc和argv,而不要使用scanf。

*The code for argc argv: * * 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. atoi-将char *转换为整数。

If you want to run the program and then insert an integer, you did it right! 如果您想运行该程序然后插入一个整数,那您做对了! you can read about atoi 您可以阅读有关atoi的信息

To run this program you should comile and run from terminal: 要运行此程序,应从终端编译并运行:

gcc a.c -o a    
./a 3

and you will receive: 您将收到:

9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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