对于每一行,使用 eg 将输入读取为字符串fgets
,然后strtok
在循环中使用 eg 来提取每个数字并使用strtol
将数字转换为整数值,然后将它们相加。
上述解决方案包含四个部分,因此让我们将其拆分并一次做一个。
对于每一行,使用 读取输入fgets
。
这非常简单,因为您所要做的就是使用外部循环并要求用户在那里输入数字,并在那里读取输入:
for (i = 1; i <= l; i++)
{
printf("Enter numbers for line number %d: ", i);
char input[128];
fgets(input, sizeof(input), stdin);
}
在循环中使用strtok
以从输入中提取每个数字。
for (i = 1; i <= l; i++)
{
/* The code to read the input... */
char *pointer = strtok(input, " ");
while (pointer != NULL)
{
/* `pointer` is now pointing to the next space-delimited number */
/* Find the next space-delimited number */
pointer = strtok(NULL, " ");
}
}
用于strtol
将数字转换为整数值。
{
/* `pointer` is now pointing to the next space-delimited number */
/* Convert string to number */
long value = strtol(pointer, NULL, 10);
/* Find the next space-delimited number... */
}
最后添加该行中的所有值。
for (i = 1; i <= l; i++)
{
long sum = 0;
/* ... */
{
long value = strtol(pointer, NULL, 10);
sum += value;
}
printf("The sum of all values on line %d is %ld\n", i, sum);
}
综上所述,我们得到以下代码:
for (i = 1; i <= l; i++)
{
printf("Enter numbers for line number %d: ", i);
char input[128];
fgets(input, sizeof(input), stdin);
long sum = 0;
char *pointer = strtok(input, " ");
while (pointer != NULL)
{
/* `pointer` is now pointing to the next space-delimited number */
/* Convert string to number */
long value = strtol(pointer, NULL, 10);
sum += value;
/* Find the next space-delimited number */
pointer = strtok(NULL, " ");
}
printf("The sum of all values on line %d is %ld\n", i, sum);
}
注意:上面的代码没有错误检查。我把它作为练习留给读者。