简体   繁体   English

从C中的.in文件读取

[英]Reading from a .in file in c

I have been coding this c file that reads in exactly 2 integers of a line of a .in file. 我一直在编码此c文件,该文件恰好读取.in文件的一行的2个整数。 So far, my code looks like this: 到目前为止,我的代码如下所示:

#include <stdio.h>

void divideTwoNums()
{
    int c = 0;
    int num1 = 0;
    int num2 = 0;
    int product = 0;
    c = getchar();

    while (c != '\n' && c != ' ' && c != '\t')
    {
        num1 = 10 * num1 + (c - '0');
        c = getchar();
    }
    c = getchar();
    while (c != '\n' && c != ' ' && c != '\t')
    {
        num2 = 10 * num2 + (c - '0');
        c = getchar();
    }
    product = num1 / num2;
    printf("%d / %d = %d\n", num1, num2, product);
}
int main(void)
{
    divideTwoNums();
    return 0;
}

When I try this code on a .in file like this: 当我在.in文件中尝试此代码时,如下所示:

96 16

My .out file reads like this: 我的.out文件的内容如下:

96 / 16 = 6

So, I know I am doing something right because the code worked for one line. 所以,我知道我做对了,因为代码只适用于一行。 However, I am stuck when it comes to multiple lines. 但是,当涉及到多行时,我陷入了困境。 Let's say my .in file reads like this: 假设我的.in文件如下所示:

96 16
50 10

My code won't work because I do not have a while loop, within the divideTwoNums method, that helps me get to a next sentence. 我的代码无法正常工作,因为在dividTwoNums方法内没有while循环,可以帮助我到达下一个句子。 Now, I tried various stuff but they were to no avail. 现在,我尝试了各种东西,但都无济于事。 Can you guys help me out? 你们能帮我吗?

edit: 编辑:

R Sahu的代码的屏幕截图

There are couple of issues you need to deal with: 您需要处理几个问题:

  1. Using a loop to divide the numbers for more lines. 使用循环将数字划分为更多行。
  2. Figuring out when to exit the loop, ie detecting when there is no more input. 找出何时退出循环,即检测何时不再有输入。

You can accomplish the first one by using a while loop in main . 您可以通过在main使用while循环来完成第一个。

int main(void)
{
    while ( 1 )
    {
       divideTwoNums();
    }
    return 0;
}

To detect that there is no input, you have do couple of things. 要检测到没有输入,您需要做几件事。

  1. Check the return value of getchar() . 检查getchar()的返回值。 If the return value is EOF, there is no more input. 如果返回值为EOF,则没有更多输入。

  2. Return a value from divideTwoNums() to indicate that there is no more input. divideTwoNums()返回一个值以指示没有更多输入。

Here's a skeletal update to the function. 这是该功能的骨架更新。 I am assuming you can complete the rest. 我假设您可以完成其余的工作。

// The return value needs to be int instead of void.
int divideTwoNums()
{
   ...

   c = getchar();
   if ( c == EOF )
   {
      // Return 0 to indicate to stop the loop.
      return 0;
   }

   ...

   // Return 1 to indicate to continue with the loop.
   return 1;
}

and change main to: 并将main更改为:

int main(void)
{
    int cont = 1;
    while ( cont )
    {
       cont = divideTwoNums();
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM