c - 我如何编写一个从命令行获取整数的 C 程序?

标签 c stdin

我想编写一个 C 程序,从标准输入获取正整数 n,并输出 n+1。它应该像这样工作

./myprog 3   
--> returns 4

./myprog -2
--> crashes

我尝试使用 scanf。但它不从命令行获取标准输入。有代码模板可以帮助我吗?谢谢。

之前我也尝试过

#include <stdio.h>
int main( ) {

   int c;

   printf( "Enter a value :");
   c = getchar( );

   printf( "\nYou entered: ");
   putchar( c );

   return 0;
}

它也不提供命令行解决方案。

最佳答案

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

int main(int argc, char * argv[])
{
     int n = atoi(argv[1]); // n from command line
     n = n + 1; // return n + 1
     printf("%d", n);

     return 0;
}

关于c - 我如何编写一个从命令行获取整数的 C 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882010/

相关文章:

python - 知道 python 脚本在由 crontab 启动时可以从 stdin 读取一些东西

c - c 中的快速 I/O,stdin/out

c - dup2、stdout 和 stderr 出现问题

c - 非阻塞 UDP 端口打开时打开文件失败

c - Short 到 Int 类型转换不起作用,为什么?

c - Valgrind: "Conditional jump or move depends on uninitialised value(s)"

谁能解释这个输出(操作系统)?

c - shell脚本 "Thread: command not found"

ssh - 如何让ssh从stdin接收密码

arrays - 从 NUL 分隔输入填充 bash 数组