![](/img/trans.png)
[英]reading in a variable number of long ints on one line using strchr and strtol
[英]Input several ints on one line, return number of ints
在學習了Java(以及其他語言)之后,我正在學習C,並且對如何處理這個簡單的問題有些困惑。 我需要編寫一個將以一行形式輸入的程序。 例如5 2 75 43 68
(僅int
),我需要返回int
的數量,它們的總和以及正數和負數。
問題在於,輸入的數量顯然是可變的-可能有一個int或七個int,但所有輸入都將在一行上。 我不確定如何使用C處理可變數量的輸入。 有人可以指出我正確的方向嗎?
要處理可變數量的輸入,您需要循環和scanf,直到按下(Ctrl + D)為止。這是一個示例:
int n,sum=0,count=0;
while(scanf("%d",&n)!=EOF)
{
sum=sum+n;
count++;
}
printf("sum=%d,count=%d",sum,count);
注意:當您按Ctrl + D時,scanf返回-1,因此輸入輸入過程終止!
干杯!
輸入一個字符串,然后搜索空格,然后轉換該位置上的每個數字並將其添加到計數和求和中。 這樣,您只需要在輸入行的緩沖區中設置上限即可; 您無需使用數組,因此既不需要限制整數的數量,也不必弄亂動態分配。
編輯:以Kerrek SB的格式,組合fgets
, strchr
和strtol
。 :P
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char buffer[200];
int numbers[100];
int main() {
char *ptr;
int cnt = 0;
fgets(&buffer[0], 200, stdin); // Get the string
ptr = strtok(buffer, " "); // Split in every space
do {
printf("Number %d: %s\n", cnt, ptr);
numbers[cnt] = strtol(ptr, NULL, 0); // Grab number
cnt++;
} while((ptr = strtok(NULL, " ")));
printf("Total numbers: %d\n", cnt);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.