0

我有一个简单的程序,它读取一行,包含 3 个数字。我需要跳过第一个数字,这是“产品”中的代码。

所以,我只需要阅读第二个和第三个字符。

我怎样才能做到这一点?

到目前为止的代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int calculate_price (number, value)
{
    int price=0;
    price= number*value;
    return price;
}

int main(void)
{
    int number, value, u,price;
    FILE  *bill, *total_price;
    bill= fopen("bill.txt","rt");
    total_price= fopen("total_price.txt","wt");

    if (bill== NULL)
    {
        printf("The file cannot be open.\nQuitting the program.\n");
        exit(1);
    }

    if (total_price== NULL)
    {
        printf("The file canno be written.\nQuitting the program.\n");
        exit(1);
    }

    while (fscanf(bill, "%d %d",&number, &value) != EOF)
    {
        u=calculate_price(number, value);
        fprintf(total_price,"The total price is %d\n", u);
    }
    printf("File created sucessfully. Check the file.\n");

}
4

4 回答 4

1

这应该适合你:

fscanf(bill, "%*d %d %d", &number, &value)

来自 scanf 文档:

可选的 '*' 赋值抑制字符:scanf() 按照转换规范的指示读取输入,但丢弃输入。不需要相应的指针参数,并且此规范不包括在 scanf() 返回的成功分配计数中。

于 2012-10-21T19:30:22.583 回答
1
int main(void)
{
    int number, value, u,price;
    int dummy; //this is a dummy var

...

while (fscanf(bill, "%d %d %d",&dummy, &number, &value) != EOF)
{
    u=calculate_price(number, value);
    fprintf(total_price,"The total price is %d\n", u);
}
printf("File created sucessfully. Check the file.\n");

编辑之前我使用 char 作为假人,因为不知何故我首先误解了这个问题,但我更正它是一个 int ...

于 2012-10-21T19:25:59.957 回答
0

尝试这样的事情:

fscanf(bill, "%d %d %d", &product, &number, &value)

...然后忽略product.

于 2012-10-21T19:25:43.843 回答
0

最简单的方法是scanf将数字转换为虚拟(未使用)变量:

int product, number, value;
...
while(fscanf(bill, "%d %d %d", &product, &number, &value)) {
    ...
}
于 2012-10-21T19:25:57.233 回答