Thread: re sizing a vector

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    1

    re sizing a vector

    so the exercise asks to develop a function that reads values from a .txt and write them into an array. The function has to return the number of values read.The only thing i know is that the array maximum lenght is 100. So i need to create a vector with 100 numbers,put the numbers from the txt into the vector,but then how do i resize the vector to have only the number of the values that are in the .txt ?

    for(a=0;a<100;a++)
    scanf("%f",&kms[a]);

    if i could exit this loop when there were no values left, it was done, but i couldn't exit it. Other way i think is using malloc function,but i dont understand how to use it.How can i solve this ?
    int ler_quilometros(float *kms)

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    check the return value of scanf to determine when there are no more numbers. then just keep the count of numbers in a variable.
    Code:
    for(a=0;a<100;a++) {
         status = scanf("%f",&kms[a]);
         if (status <= 0) break;
    }
    after the break, the variable 'a' has the actual number of values.
    scanf will return 0 if the file has data but it can't be converted to a floating point number
    scanf will return less than 0 at end of file

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Odd Sizing Issues
    By Gerread in forum Windows Programming
    Replies: 4
    Last Post: 06-01-2007, 08:38 PM
  2. sizing problem
    By beene in forum Game Programming
    Replies: 5
    Last Post: 11-14-2006, 03:38 AM
  3. Window Sizing Question
    By Mastadex in forum Windows Programming
    Replies: 10
    Last Post: 05-26-2006, 09:42 AM
  4. Array Sizing
    By elliott in forum C++ Programming
    Replies: 1
    Last Post: 12-25-2005, 09:41 AM
  5. Sizing Memory Q.
    By penney in forum C Programming
    Replies: 2
    Last Post: 04-23-2003, 12:33 PM