![](/img/trans.png)
[英]C program to convert input string of space separated ints into an int array
[英]Input ints separated by whitespace and pass them to an int array
我試圖用C編寫一個程序,其中用戶輸入由空格分隔的定義數量的整數(在本例中為5個整數)。 然后,將輸入存儲在int數組中,最后,可以將其存儲在char數組中。
當程序要求輸入時,作為該程序如何工作的示例:
Input: 20 5 63 4 127
該程序的輸出應為:
Output: 20 5 63 4 127
到目前為止,這是我編寫的內容,但是我不知道如何將輸入轉換為int數組。 請注意,我事先知道輸入的長度(在這種情況下,如上所述,為5 ints)。
// Input: 20 5 63 4 127
// Ask for user input.
// Store the input in this int array.
int input_int_array[5];
unsigned char char_array[5];
for(int i=0;i<5;i++)
{
char_array[i]=input_int_array[i];
printf("%d ", char_array[i]);
}
// Should print: 20 5 63 4 127
您可能希望使用scanf()
將用戶輸入作為整數讀取到int
數組中:
#include <stdio.h>
int main() {
int input_int_array[5];
// Ask for user input.
printf("input 5 numbers: ");
for (int i = 0; i < 5; i++) {
// Store the input into the array.
if (scanf("%d", &input_int_array[i]) != 1)
return 1;
}
// Output the contents of the array:
for (int i = 0; i < 5; i++) {
printf("%d ", input_int_array[i]);
}
printf("\n");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.