user2759575 user2759575 - 1 year ago 99
C Question

Returning the nth word in a file

I have a file with a bunch of words (separated by spaces). I'm trying to get the nth word.

I'm looping through each character of the file. I count the number of words by adding 1 to a counter when it gets to a space. If the counter value is equal to n (i.e. it's at the word I want), I want add the current character to the char array. Since n is an int, I use sprintf to convert to a char and then use strncat to add the letter to the word.

Here's the code:

int n;
int count = 1;
char word[100];
char converted_char[32];

while ((n = fgetc(file)) != EOF) {
if ((n) == ' ')

if ((count) == wordNumber)
sprintf(converted_char, "%d", n);
strncat(word, converted_char, 1);

printf("The word is: %s", word);

The problem is, the word is returned an an int. I tried replacing %s with %c which gave me an error. What am I doing wrong?

As well, I'm open to suggestions of better ways to do this.

Answer Source

try this:

#include <stdio.h>

int main(void){
    int wordNumber = 3;
    FILE *file = fopen("data.txt", "r");
    int count = 0;
    char word[100];

    while (fscanf(file, "%99s", word) != EOF) {
        if(++count == wordNumber){
            printf("The word is: %s\n", word);

    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download