Thread: How to read a line of integers?

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    1

    How to read a line of integers?

    If i want to read 10 integers from a file i would write this:

    Code:
    int main(){
    
        int i;
    
        freopen("numbers.txt","r",stdin);
    
        for(i = 0; i <= 10; i++){
            scanf("%d",&i);
            printf("%d",i);
        }
        fclose(stdin);
    
        return 0;
    }
    But how to write a loop if i don't know how many integers will be in a file?

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Take a look at fread .
    It will return NULL when it reads out the file....

  3. #3
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    Do a "forever loop" (with a break inside to get out)

    Code:
    for (;;) {
        /* ... */
        if (NEED_TO_EXIT_LOOP) break;
        /* ... */
    }

  4. #4
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197
    it would be better to use fopen since freopen works mostly when the file had already been opened.

  5. #5
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197
    Code:
    FILE *fp = fopen("numbers.txt", "rb");
    
    int k = 0;
    while(  k < 10)
    {
         fscanf(fp, "%d", &i);
          k++;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-26-2012, 10:50 AM
  2. Replies: 21
    Last Post: 08-07-2011, 09:55 PM
  3. Read text file line by line and write lines to other files
    By magische_vogel in forum C Programming
    Replies: 10
    Last Post: 01-23-2011, 10:51 AM
  4. Read strings line by line until Ctrl+C is pressed
    By r00t in forum C Programming
    Replies: 25
    Last Post: 11-17-2009, 04:18 AM
  5. Reading a buffer line by line, while using system read
    By Hammad Saleem in forum C Programming
    Replies: 9
    Last Post: 05-27-2008, 05:41 AM