初学C,有点吃力。
我正在读取像这样的输入:
9, 344, 100
10, 0, 469
...
我正试图将每一行分组,以便我可以将每3个数字作为函数中的参数发送。
我一直在尝试使用scanf
,但因为它映射到内存地址,所以我在每行之后保留数字时有问题。我不知道我将有多少行数据所以我不能创建一定数量的数组。此外,我仅限于<stdio.h>
中的函数。
如果我使用scanf
,无论如何我都要避免使用malloc?
我在下面附上了一个想法。寻找关于scanf
如何工作的建议和一些澄清。
如果我在这里遗漏了一些明显的东西,我道歉。
int main() {
int i = 0;
int arr[9]; //9 is just a test number to see if I can get 3 lines of input
char c;
while ((c = getchar()) != EOF) {
scanf("%d", &arr[i]);
scanf("%d", &arr[i + 1]);
scanf("%d", &arr[i + 2]);
printf("%d, %d, %dn", arr[i],
arr[i + 1], arr[i + 2]); //serves only to check the input at this point
//at this point I want to send arr 1 to 3 to a function
i += 3;
}
}
这段代码的输出是一堆内存地址和一些正确的值。像这样:
0, 73896, 0
0, 100, -473670944
当它应该读:
0, 200, 0
0, 100, 54
int main(){
char c;
while ((c=getchar()) != EOF){
if (c != 'n'){
int a;
scanf("%d", &a);
printf("%d ", a);
}
printf("n");
}
}
这段代码正确地打印出输入,但不允许我在while块中多次使用scanf
而不会出现内存问题。
一种选择是同时扫描所有三个。您还需要匹配输入中的逗号(,
)。
的例子:
#include <stdio.h>
int main() {
int arr[9];
int i = 0;
for(; i + 3 <= sizeof arr / sizeof *arr // check that there is room in "arr"
&& // and only then, scan:
scanf(" %d, %d, %d", &arr[i], &arr[i+1], &arr[i+2]) == 3;
i += 3)
{
printf("%d, %d, %dn", arr[i], arr[i+1], arr[i+2] );
}
}
我宁愿使用fgets
和sscanf
。
char buff[64];
/* .......... */
if(fgets(buff, 63, stdin) != NULL)
{
if(sscanf(buff, "%d,%d,%d", &arr[i], &arr[i + 1], &arr[i + 2]) != 3)
{
/* handle scanf error */
}
}
else
{
/* handle I/O error / EOF */
}