[英]C: Reading multiple values with scanf and saving them into an array
我找到了問題第一部分的答案(如何使用scanf讀取多個值),但它似乎對我不起作用(我認為這是因為將值放入數組中,也可能是因為我正在檢查如果給定的值肯定是6個整數):
我正在編寫一個將4個三角形的坐標存儲在數組中的程序。 每行有6個值,並存儲一個三角形的坐標。 我想一次讀取6個坐標,並分別對4個三角形進行此操作。
int tab[4][6];
for (int i = 0; i < 4; i++){
while (scanf("%d %d %d %d %d %d", &tab[i][0], &tab[i][1], &tab[i][2], &tab[i][3], &tab[i][4], &tab[i][5]) != 6){
printf("Error, try again: ");
while (getchar() != '\n'){}
}
}
因此,例如,如果第一個三角形的坐標為(2,1),(5,6),(2,7),那么我想輸入:“ 2 1 5 6 2 7”,因此我想要它按照我輸入的順序,用上述數字填充數組的第一行。
顯然,它不起作用,在給出第一行后,程序停止了工作(未完成工作,它停止了)。
調試后(給出第一行后),我得到此錯誤:“ xxx.exe中0x0FDCC28C(msvcr120d.dll)的未處理異常:0xC0000005:寫入文件0xCCCCCCCC的訪問沖突。”
如何解決?
例如,在檢測到輸入錯誤時,您需要減去指針i->
#include <stdio.h>
int main(int argc, const char * argv[]) {
int tab[4][6];
for (int i = 0; i < 4; i++){
printf("Enter 6 values \n");
int retVal=scanf("%d %d %d %d %d %d", &tab[i][0], &tab[i][1], &tab[i][2], &tab[i][3], &tab[i][4], &tab[i][5]);
if (retVal == 6) {
printf("You did enter -> %d %d %d %d %d %d\n",tab[i][0],tab[i][1],tab[i][2],tab[i][3],tab[i][4],tab[i][5]);
} else {
printf("Error entering values.. (Enter numbers). \n");
while (getchar() != '\n'){}
i--;
}
}
return 0;
}
不清楚為什么OP的代碼失敗而不發布使用的輸入和先前的代碼。
如何解決?
使用fgets()
讀取一行用戶輸入。 避免在先前的代碼中將scanf()
與fgets()
混合使用。 然后解析緩沖區。 最后使用" %n"
查找成功和其他文本。
int tab[4][6];
char buf[6*12 * 2]; // Use a buffer twice expected max needs
for (int i = 0; i < 4; i++) {
while (1) {
if (fgets(buf, size buf, stdin) == NULL) {
return "Failed to read enough data"; // Handle end-of-file in some fashion
}
int n = 0;
sscanf(buf, "%d%d%d%d%d%d %n",
&tab[i][0], &tab[i][1], &tab[i][2], &tab[i][3], &tab[i][4], &tab[i][5], &n);
if (n > 0 && buf[n] == 0) {
break; // Success!
}
printf("Error - bad input, try again: ");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.