[英]C, reading multiple numbers from a single scanf
我有一個賦值,要求我采用單個scanf並對幾個整數執行一些數學運算。 輸入中的第一個數字設置要遵循的整數數量,即:3 45 67 18應解釋為N var1 var2 var3和4 100 23 76 92應解釋為N var1 var2 var3 var4。 我無法按照第一次迭代的指示制作程序,但它確實可以正常工作。 我通過簡單地將scanf放在一個運行N次的循環中並將剩余的數字存儲在一個數組n [1000]中來完成存儲var1 var2 ... varN。 就像我說的那樣,程序有效......但是它並沒有按照指配的方式工作。 作業提供的樣本運行應該是:
Please enter n followed by n numbers: 3 6 12 17
Test case #1: 6 is NOT abundant.
Test case #2: 12 is abundant.
Test case #3: 17 is NOT abundant.
我的程序輸出是:
Please enter n followed by n numbers: 3
6
12
17
Test case #1: 6 is NOT abundant.
Test case #2: 12 is abundant.
Test case #3: 17 is NOT abundant.
這是我的程序的鏈接 。 我已經閱讀了許多類似的問題,但大多數似乎都忽視了scanf的使用,而不是從控制台捕獲輸入的其他方法。 這篇文章非常接近我正在尋找的答案,除了我需要動態設定數量的變量。 我有一種感覺,我需要使用malloc函數,但我不太確定如何使用它,仍然完成一行scanf輸入。
謝謝
好吧,我測試了它,你確實可以用scanf
做到這一點。
#include<stdio.h>
int main(){
int total = 0;
int args;
char newline;
do{
int temp;
args = scanf( "%d%c", &temp, &newline );
if( args > 0 )
total += temp;
puts( "Internal loop print test");
} while( newline != '\n' );
printf( "\n\n%d", total );
return 0;
}
控制台日志:
1 2 3 9
Internal loop print test
Internal loop print test
Internal loop print test
Internal loop print test
15
編輯:由於幾個已知的漏洞問題,我從不使用scanf
系列,但我甚至沒有嘗試使用scanf
。 我以為它會讀到換行符,但它對scanf
工作得很好。 Aniket的評論讓我想嘗試一下。
以下代碼對我有用:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n[1000],i,j,sum,size;
printf("Please enter n followed by n numbers: ");
scanf("%d",&n[0]);
for (i=1;i<=n[0];i++)
scanf("%d",&n[i]);
/* Debug: Automatically generate numbers from 1 to n[0] */
//n[i]=i
for (i=1;i<=n[0];i++)
{
/* Debug: See what numbers are being used in sum - Part 1*/
//printf("\nFactors < %d of %d: ",n[i]/2,n[i]);
sum=0;
for (j=1;j<=n[i]/2;j++)
{
if (n[i]%j==0)
{
/* Debug: See what numbers are being used in sum - Part 2*/
//printf("%d ",j);
sum+=j;
}
}
printf("Test case #%d: %d is%sabundant.\n",i,n[i],(sum>n[i])?" ":" NOT ");
/* Debug: See what numbers are being used in sum - Part 3*/
//printf("(%d)\n",sum);
}
system("PAUSE");
return 0;
}
Aslai你的回答讓我感到困惑,因為我無法看到你的代碼將如何完成與我所做的不同。 因此,當我調試以查看返回的scanf時,我注意到scanf實際上在每個空格后返回,而不是像我想的那樣“輸入”或“\\ n”。 所以我簡化了我的第一個for循環,一切正常。 我是否正確地說,只要有足夠的后續scanf調用,來自一個scanf的輸入將滿足后續scanf的變量賦值? 換句話說,如果我在單次掃描期間輸入3 25 17,那么我可以將這些數字中的每一個分配給變量以及后續的scanf調用而無需按Enter鍵嗎?
scanf("%d",&var1); //(where var1=3)
scanf("%d",&var2); //(where var2=25)
scanf("%d",&var3); //(where var3=17)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.