问题描述:

I have an assignment that tasks me with reading from a file that contains a series of numbers in ASCII decimal format and convert them to integers. I've made a function that does this but I don't know what the numbers are in the file. How do I see open a file that contains these type of numbers? Whenever I open it in a text editor or some other program I end up with series of integer numbers. Is this what it should look like?

Thank you in advance

网友答案:

Assuming you have a text file containing a series of numbers in ASCII decimal format, one number per line, you can easily accomplish your task using a C program like this one:

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

#define MAX_LINE_LEN  (32)

int main ( int argc, char * argv[] )
{
    FILE * pf;
    char line[ MAX_LINE_LEN ];

    /* open text file for reading */
    pf = fopen( "integers.txt", "r" );

    if( !pf )
    {
        printf("error opening input file.\n");
        return 1;
    }

    /* loop though the lines of the file */
    while( fgets( line, MAX_LINE_LEN, pf ) )
    {
        /* convert ASCII to integer */
        int n = atoi( line );

        /* display integer */
        printf("%d\n", n );
    }

    /* close text file */
    fclose( pf );

    return 0;
}

/* eof */ 
相关阅读:
Top