0

I want to be able to ask the user which column he wants to print from the input file. The input file is a standard text file that has 4 columns (as described by the code in the global variables) that are separated by space (which is what I'm using to separate each line in the getline function.)

Thank you.

#include <stdio.h>
#include <string.h>
#define LINE_SIZE 256
#define COL_NUM 3

int main()
{
    char line[LINE_SIZE];
    char *ptr;
    int column;
    FILE * fp = fopen("input.txt", "r");

    while(!feof(fp)){                    // if not the end of file
        fgets(line, sizeof(line), fp);   // get one line each time
        ptr = strtok(line, " ");         // split line by space
        column = 1;                      // starting column is one
        while(ptr != NULL)               // if the line is not finished
        {
            if(column == COL_NUM){
                printf("%s\n", ptr);     // print what we got
                ptr = strtok(NULL, " "); // and keep splitting
            }
            ptr = strtok(NULL, " ");     // and keep splitting
            column++;
        }
    }
    fclose(fp);
    return 0;
}
duncan
  • 1,161
  • 8
  • 14
  • 4
    Please see [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/q/5431941/2173917) – Sourav Ghosh Jun 23 '16 at 14:56
  • 1
    assuming you are happy to use console, I suggest you read up on things like printf() getchar() scanf() etc. I'd recommend tutorialspoint –  Jun 23 '16 at 15:02

1 Answers1

0

First, you need to ask user to input the column number, after that you need th check if the input number is between 1 and 4, and then print the line which you selected.

int input = 0;
int i = 0;

printf("Select a column number!\n");
scanf("%d", &input);

if (input>0 && input <5) 
{
    for (i=1; i<5; i++) 
    {
        fgets(line, sizeof(line), fp);
        if (input == i)
            printf("The column is %s\n", line);
    }

}
Mirakurun
  • 4,859
  • 5
  • 16
  • 32