【问题标题】:Reading file input into a char array in c将文件输入读入c中的char数组
【发布时间】:2015-07-11 22:31:06
【问题描述】:

我正在上 C 语言入门编程课,但我在本学期的期末项目中遇到了一些问题。我们必须获取一个输入文件,该文件将在不同的行上包含多项式方程,然后我们必须对这些方程中的每一个进行导数。我正在尝试将方程读入一个字符数组,以便我可以处理该数组以获取导数。我的逻辑目前要求程序一次读取一行,以便我可以通过我的函数运行相应的数组并获取导数。然而,我正在努力弄清楚如何做到这一点,因为我们不知道将要测试的方程的长度。 我的主函数目前看起来像这样,执行上述内容的代码需要在调用函数一之前进入 do 循环。这三个函数都是 void 类型。

int main(void)
{
    char input [40], output [40];
    do
    {

        function1( &input);
        function2 (&input, &output);
        function3(&output);

    }while(!feof(ifp))

}

感谢您的帮助。

【问题讨论】:

  • 不要使用 feof() 仅在尝试读取文件末尾之后才是正确的。
  • 糟糕的函数名。对函数和变量使用有意义的名称,名称表明用途或内容或(对于函数)要执行的活动。
  • 来自help center请求家庭作业帮助的问题必须包括您迄今为止为解决问题所做的工作的总结,以及您遇到的困难的描述 复制/粘贴你的 main() 函数的样子,而不实现它调用的函数不是到目前为止你已经完成的工作我该怎么做这个? 不构成对您解决它的困难的描述

标签: c arrays file input


【解决方案1】:

以下代码将帮助您入门。

由你来实现 calculateDerative() 函数

在C编程课程结束时,以下代码 应该是你可以在睡梦中做的事情

#include <stdio.h>
#include <stdlib.h> // exit(), EXIT_FAILURE

#define MAX_INPUT_LEN  (40)
#define MAX_OUTPUT_LEN (40)

//void function1( char * pInput );
//void function2( char * pInput, char * pOutput );
//void function3( char * pOutput );
void calculateDerivative( char* pInput, char* pOutput );

int main(void)
{
    FILE *ofp = NULL;
    FILE *ifp = NULL;

    if( NULL == (ifp = fopen( "inputFileName", "r" ) ) )
    { // then fopen failed
        perror( "fopen for read failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    if( NULL == (ofp = fopen( "outputFileName", "w" ) ) )
    { // then fopen failed
        perror( "fopen for write failed" );
        fclose( ifp );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    char input [MAX_INPUT_LEN], output [MAX_OUTPUT_LEN];

    while( fgets( input, sizeof(input), ifp ) ) // stay in loop until NULL returned
    {
        //function1( input ); // already have input available
        //function2 (input, output ); // process from input to output
        calculateDerivative( input, output );
        //function3( output) ; // write output to output file
        if( 1 != fwrite( output, strlen(output), 1, ofp ) )
        { // then fwrite failed
            perror( "fwrite failed" );
            fclose( ifp );
            fclose( ofp );
            exit( EXIT_FAILURE )
        }

        // implied else, fwrite successful

    } // end while

    fclose( ifp );
    fclose( ofp );

    return (0);
} // end function: main

【讨论】:

  • 如果在你的系统上可用,readline() 函数会比 fgets() 更好
猜你喜欢
  • 1970-01-01
  • 2011-05-21
  • 2017-01-20
  • 2017-01-13
  • 2012-11-03
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多