如何讓程序在程序運行之前讀取任何兩個整數輸入? 我要輸出到這個樣子,x和y被任何變量(我使用Cygwin)類型:如何讀取數字作爲命令參數?
$ ./axy
x和y x的
和產品和y
我用int main(int argc, char *argv[])
。我試圖將argv[2]
分配到x
和argv[3]
到y
,但是當我編譯程序時,它說分配會從指針中取得整數,而不進行轉換。這是什麼意思,我該如何解決?
如何讓程序在程序運行之前讀取任何兩個整數輸入? 我要輸出到這個樣子,x和y被任何變量(我使用Cygwin)類型:如何讀取數字作爲命令參數?
$ ./axy
x和y x的
和產品和y
我用int main(int argc, char *argv[])
。我試圖將argv[2]
分配到x
和argv[3]
到y
,但是當我編譯程序時,它說分配會從指針中取得整數,而不進行轉換。這是什麼意思,我該如何解決?
假設C語言:
[試圖教你魚,而不是提供一條魚。祝你好運!]
假設你正在使用bash,你可以使用$ 1,$ 2等這些參數。但是,如果你正在使用C,你的代碼應該看起來更像這樣:
#include <stdio.h>
#include <stdlib.h>
main(int argc, char *argv[]) {
if(argc<=1) {
printf("You did not feed me arguments, I will die now :(...");
exit(1);
} //otherwise continue on our merry way....
int arg1 = atoi(argv[1]); //argv[0] is the program name
//atoi = ascii to int
//Lets get a-crackin!
}
希望這會有所幫助。
首先,如果運行C程序作爲
./axy
則是的argv [0],x是的argv [1],並且y是的argv [2] ,因爲C數組是基於0的(即數組中的第一項被索引爲0.)
認識到argv是一個數組(或者我一直認爲它是一個ARGument Vector,儘管你可能會想到它作爲一個ARGument Values的數組),所以你需要將字符串轉換爲整數秒。幸運的是,C具有將ASCII轉換爲整數的庫函數。查看stdlib.h文檔。
祝你好運!
在命令行參數中,char * argv []是字符串類型。我們需要將它轉換爲整數。爲此,我們的類型轉換,但在OOP中,我們用的atoi函數(方法),它的工作原理是強制類型轉換做到這一點(指將一個數據類型到其它的方法)
int arg1 = argv[1];
不會工作,因爲它是一個數組指針持有的argv[0]....argv[n]
所有地址來獲取值的argv[..]
假設argv[1]
你必須寫:
int n=*argv[1]-'0'; // Direct atoi
我的代碼是這樣的。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
// argc is number of arguments given including a.out in command line
// argv is a list of string containing command line arguments
int total = 0;
int i;
char *value;
for(i = 1; i < argc; i++)
{
// The integers given is read as (char *)
value = argv[i];
printf("Command line index: %d value: %s in ascii: %d\n", i, value, *value);
// Convert ascii to integer.
// atoi function is defined in stdlib.h
total += atoi(value);
}
// .2f limits the decimals to two digits after '.'
printf("Total of given integers is %d\n", total);
}
您使用什麼語言? – sykora 2009-02-07 05:58:25
您的教科書是否提供了有關使用命令參數的示例? – mmcdole 2009-02-07 06:05:40
我正在使用c語言。 我們只介紹了這本書的前三章,這一章已經過了一半,對我來說完全是廢話。當我缺席時,老師報道了這一點,所以我無能爲力! – Kaity 2009-02-07 07:24:01