[英]C: integers not printing correctly
(大家好。我嘗試搜索目前遇到的問題,到目前為止似乎找不到解決方案。我是編程新手,目前正在學習C,但是我是一個完全菜鳥,所以我提前道歉如果我犯了一個愚蠢的錯誤。)
問題出在這里:Im tryna掃描4個整數,並使用while循環打印它們的值。 問題是,數字被打印為瘋狂的長數字,而不是輸入的整數。 我嘗試掃描和打印單個int,但打印效果很好,但是一旦使用多個int,它就會開始擰緊。
這是我的代碼:
#include <stdio.h>
int main()
{
int i, n1,n2,n3,n4;
printf("Enter 4 numbers.");
for(i=0;i<4;i++)
{
printf("\n\nEnter number %d: ", i+1);
scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4);
printf("%d,%d,%d,%d", n1,n2,n3,n4);
}
}
兩件事情:
scanf()
給出的輸入格式應與輸入值完全匹配,以成功進行掃描 。 [你需要有,
在你輸入] scanf()
是否成功,以確保正確掃描值。 scanf()
返回成功匹配和掃描的項目數。 因此,您應該將代碼更改為
if ( scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4) == 4)
{
// use n1, n2, n3, n4
}
else
//don't use them, return some error.
注意:始終初始化局部變量。 很多時候,它將使您免於寫前讀取方案的不確定行為。
另外,[也許?]不需要for
循環,因為您一次要掃描所有四個數字。
當您擁有scanf("%d,%d,%d,%d", &n1,&n2,&n3,&n4);
您必須按1,2,3,4
的要求輸入(需要commas
)
您說要讀取4個數字,並且有一個scanf
可以獲取4個數字。 因此,這里不需要循環。 如果要循環,則每次在循環內獲取one number
。
您正在循環4次,希望在每個循環中讀取4個數字...
一般而言, scanf()
對於解析可能與預期格式不匹配的任何類型的輸入來說是一個差勁的工具-而且沒有什么比用戶輸入更善變了。 我通常建議讀取整個輸入行(通過fgets()
),然后根據需要在內存中對其進行解析(在這種情況下,這可能意味着使用strtol()
並檢查通過解析了多少輸入字符串)其第二個參數)。
例如, 這更加健壯:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define LINELEN_MAX 100
int main()
{
int i;
char input[ LINELEN_MAX ];
char * current;
char * end;
while ( 1 )
{
// whitespaces or commas do not matter,
// and neither does the amount of numbers.
puts( "Enter numbers, or 'q' to quit." );
if ( fgets( input, LINELEN_MAX, stdin ) == NULL )
{
puts( "Error on read." );
return EXIT_FAILURE;
}
if ( *input == 'q' )
{
puts( "Quitting." );
return EXIT_SUCCESS;
}
if ( input[ strlen( input ) - 1 ] != '\n' )
{
puts( "Line exceeded maximum width." );
return EXIT_FAILURE;
}
current = input;
end = input;
while ( *current )
{
if ( !isdigit( *current ) )
{
// skip non-digits
++current;
}
else
{
// parse 1..n digits and print
printf( "%ld\n", strtol( current, &end, 10 ) );
current = end;
}
}
}
}
原因之一可能是您的所有值都被打印在同一行上,而它們之間沒有任何空格。
基本上,您正在一行中連續打印4個數字,這使其看起來像一個大數字。
我建議您添加一個新的行格式說明符。(如果您是新手,那么您可能不理解這一點,因此這里有一些有用的鏈接)
http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
還有一個問題,您正在讀取4個數字4次,即總共要讀取16個變量。 對於此代碼,您實際上不需要for循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.