wad
wad

Reputation: 2827

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,

Where am I wrong? Thanks.

#include <stdio.h>

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

Upvotes: 0

Views: 4906

Answers (4)

nachiketkulk
nachiketkulk

Reputation: 1261

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

Upvotes: 1

Yosef Alon
Yosef Alon

Reputation: 78

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

Upvotes: 1

James Deng
James Deng

Reputation: 162

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

Upvotes: 2

Ryan
Ryan

Reputation: 14659

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

Upvotes: 1

Related Questions