Hi there
I am really new in C programming (about 3 weeks). Before I begin my question I have to excuse because of my bad English.
My question is on reading a file that contains double and integer type numbers.
For reading file I use fgets() that read a line and save it to an array ( I define the string array as: char [100][150]).
But know how I can access to my values in array. In array I have each line of my data as string.
My other codes are based on it.
I have to say that, my file is exported from excel as text file and all data separated by space.

Yours help truly appreciated,
Thanks

Recommended Answers

All 31 Replies

>>But know how I can access to my values in array
Is that the question -- how to extract each of the numbers in the string ? extract them using sscanf(). There is a simple example

int main()
{
    char line[] = "123 234.56 789";
    int a, b;
    float c;
    sscanf(line,"%d %f %d", &a, &c, &b);
    printf("%d %f %d", a, c, b);
}

question:

does each line of your data always have the same number of INTs and FLOATs, and are they always found in the same order?

if so, Dragon's suggestion for "sscanf()" is perfect. if not, you will need a more complex routine, perhaps using "strtok()"

Hi
Thanks for your attention.
All I have done is this code that made error. And numbers don’t save in new array. Only my and zeros print on console.
Also in my file I know only the row of integer value.

#include <stdio.h>

int main(void)
{
      
   char input[150][350];
   char line[350];
   int i,j=0;
   double num[1000];  /*But i don't Know the exact num*/
   FILE *get_input;
   get_input=fopen("input.inp","r");
   
   if (get_input!=NULL)
   {
       while (fgets(line,sizeof line,get_input)!=NULL)
       {
             strcpy(input[i],line);
             printf("My Inputs%s\n",input[i]);
             i++;
       }
   }
   else
   {
       perror("File cannot be found");
   }
   i=0;
   while (line[i]!=EOF)
   {
         sscanf(input[i],"%f",&num[i]);
         printf("My Numeric Array%f",num[i]); 
         /*Only print text and zeros finally because of array size an error*/
         i++;
   }
   
   system("pause");
   return 0;
}

>>strcpy(input,line);
What's the initial value of i? Answer: undefined because you didn't set it to 0 before that loop started.

>> while (line!=EOF)
line will NEVER EVER be EOF. So that's the wrong way to code that loop. What you need to do is create another integer that counts the number of lines read so that in this loop you can check the number of lines. You have already done that to an extent -- in the loop that reads the data you are using variable i but then the program uses that same variable over again. Use a different counter. for(i = 0; i < counter; i++)

Ok,
I think I have another mistake in second loop. Because I send each line to input[] array but in second loop I use line[] array for getting number from each line. I correct this as bellow but encounter an error that you can't compare pointer and integer. I think that the arrays are pointer but what is this error source.
What I have to do to solve these.

Thank you,

while (input[i]!=EOF)
   {
         sscanf(input[i],"%f",&num[i]);
         printf("My Numeric Array%f",num[i]); 
         
         i++;
   }

In order to learn how to program you first need to learn how to read. Please read my previous very very carefully and you will find the answer to your problem.

HI Sir
I wish to write a program that can do the following


Write a program to count and print the total number of:

upper case letters, i.e. ‘A’ to ‘Z’
lower case letters, i.e. ‘a’ to ‘z’
digits, i.e. ‘0’ to ‘9’
spaces
newlines
other characters.
entered on standard input or redirected to standard input from a file. Submit the .c file you write to do this via the submission box below.


Hint 1: You should design this program before coding it.

Hint 2: Remember in C, all characters are represented by small integers in the range 0 to 255.

Hint 3: when you compile you program if you create and executable called ‘ex_e’, you will be able to test the program using the following:

ex_e < testdata.txt

where testdata.txt is a file with your test data in it. Try and think about the sort of test data you might need to test your program.

HI Sir
I wish to write a program that can do the following

I can assure you that no one over here will prevent you from doing so.

It is customary to read the rules of the forum if you are posting for the first time.
Allow me to invite you to do that now. Click here
For further help read this and this
And one more thing. It is alright to make your own new thread, next time you want to ask a question.
Welcome!! :)

I can assure you that no one over here will prevent you from doing so.

i might.

i might.

Oh, yeah? I would like you to try, stupendous man ;)

commented: Watterson rocked the funny pages. +1

silly mortal, you doubt my powers?

watch me battle my way through pedantic digressions about the dangers of pseudo-randomness and the evils of scanf, while flying by the seat of my pants deep into the lair of non-error-checked command line input. all in the name of clarity i say!

whoops... here comes Naure

*ahem* now if you'll excuse me, i believe i have other um... threads to rescue.

commented: Hehe. Stupendous man saves the moment once again. +7

Ok,
As you said I defined i variable and declare another variable called cnt. The piece of code that I changed is below. But if I use cnt=0 the loop never entered. And when I changed cnt to 1 the result are same as my previous while loop.
I can't find the error please notice this,

for(i=0,cnt=0;i<cnt;i++,cnt++)
   {     
         sscanf(input[i],"%f",&num[cnt]);
         printf("My Numeric Array%f",num[cnt]);  
   }

for(i=0,cnt=0;i<cnt;i++,cnt++) Well, if i = 0 and cnt = 0 this i < cnt will never allow the loop to execute, because i is never smaller than cnt. Don't you think?

I know the loop don't enter. if you see i mentioned that i my question. My question is what i have to do to get the numbers from my text array.

I know the loop don't enter. if you see i mentioned that i my question.

Yes, he saw that. He also explained your problem for you, so that you can come up with a solution yourself.
This is a great attitude if you want people to ignore your problem, but I'm in a fairly good mood, so: for(int i=0; i< (how many elements are in your array); i++) Now remove all the cnt's because they don't make any sense.

Yes, he saw that. He also explained your problem for you, so that you can come up with a solution yourself.
.

he :icon_eek: Aia's avatar looks female to me :)

he :icon_eek: Aia's avatar looks female to me :)

Whoops. I have avatars switched of, so I didn't notice it... :icon_redface:

I used this loop before this someone said don't use that define as such, please read the main program (I want to read double data from string array that made from file). When I use these loops I can't access the string array anyway. And when I try to print I see 0.0000.
If I want to describe the case in my input [] array now I have the string of numbers in double format I want to have access to each numbers in second array (i.e. num[]).
Please

for(i=0;i<150;i++)
   {     
         sscanf(input[i],"%f",num[i]);
         printf("My Numeric Array%f",num[i]); 
         /*This only print the string and 0.00000 for all of my num[]*/  
   }

he :icon_eek: Aia's avatar looks female to me :)

Whoops. I have avatars switched of, so I didn't notice it... :icon_redface:

Vanity, oh, vanity.
Everything is vanity.
What today is,
Tomorrow does not exist.
Must appearance still persist?
Forgive me for the indulgence of putting the thought into rhyme.


I'm not quite sure of what you want. Perhaps something like this?

for ( i = 0; i < 150; i++ )
{     
         if ( sscanf( input[i], "%f",  &num[i] ) == 1 )
             printf( "My Numeric Array[%d] = %f\n", i, num[i] );
         else
             break; 
         
}

Hi,

The problem of reading each line and getting the values didn't solved. However I decide to use this snippet for getting the double values from file.
In the following code I used fscanf() for getting each character at a time and then compare that with END keyword (This key is used for determining end of each line) and if the END founded I want to exit this innermost loop and continue with next row of numeric array.
When I use this code I can get values in double format but I can't save them in two dimensional arrays. Because the condition for next row never be true. But I don't know why? Why the temp never be equal to END. When I use watch for debugging I saw that temp be equal to END but if statement always is false.
Excuse me for my bad English but please some help

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

main()
{
      char ch;
      char each[20];
      char *endptr;
      char nrow[4]="END";  /*For determining end of each line*/
      double num[150][300];
      int r=0;
      int c=0;
      
      char temp[4];
      FILE *fp;
      fp=fopen("input.inp","r");
      
      if (fp==NULL)
      {
      printf("Error Finding File");
      exit(1);
      }
       
      ch=fscanf(fp,"%s",&each);
      for (;ch!=EOF;r++)
          { 
             for (c=0;c<30;c++)
                {
                    strncpy(temp,each,3);
                    if (temp==nrow) /*decide that when i have to go next row*/ 
                    break;
                    
                    else
                    {
                       num[r][c]=strtod(each,&endptr);
                       printf("%s\t %g\n",each,num[r][c]);
                       ch=fscanf(fp,"%s",&each);
                    }
                } 
          }  
      system("pause");
      return 0;
}

line 25: fscanf() returns an int, not a char.

line 26: should check for both 0 and EOF.

line 31: you can't compare two strings like that. You have to call strcmp() if( strcmp( temp, nrow) == 0) line 32: That break will stop the loop started on 28 and do nothing for the earlier loop. If that's what you want then its ok.

lines 34, 35 and 39 are unnecessary. You don't need an else after that if statement on line 31.

i've become kind of confused as to what it is you are trying to do.

i've become kind of confused as to what it is you are trying to do.

Are you kidding? Mind reading should be the first skill you must hone ;)

>When I use this code I can get values in double format but I can't save them in two dimensional arrays.
If what you want is to read floats from file and store it in a separate array:

double numbers[150];
int i = 0; /* index of loop */

/* start reading line after line, looking for floating-points */
while ( fscanf( fp, "%f", &number[i] ) == 1 )
{
    /* do something here */

    ++i; /* to move to next number in the array */
    /* Do not exceed the space for numbers */
    if ( i > 150 )
        break;
}

if what you want is to store the strings in a multidimensional array:

char strings[150][256];
int i = 0;

while( fscanf( fp, "%s", strings[i] ) == 1 )
{
     <snip>
     ....
    ++i;
    /* do not go beyond 150 */
    if ( i > 150 )
        break;
}
commented: funnay :-) +1

Thanks Very much,
I can get the doubles to my numeric array. But i please say me can i iterate between characters in a string line. If i can iterate between characters then i can save them in an array.
Yours truly, Thanks

I went back and reread this entire thread and no where have you ever told us what the actual file looks like. It will help if you post a line or two from the file so that we know what your program need to read.

^ thank you. i was concerned that i was losing my own reading comprehension skills.

I went back and reread this entire thread and no where have you ever told us what the actual file looks like. It will help if you post a line or two from the file so that we know what your program need to read.

OK,
My file is something like this.

0.55  0.33  0.15  0.15  0.15  0.15  0.15  0.15  0.15  0.15  0.15  …
0.201506024096386  0.186746987951807  0.20210843373494 …
.
.
.

I imported each line in a string array ( I write the codes in earlier posts). Then I want to use these numbers for my calculation in next step. I have to say that with your suggestion and some reading around I can get each character and save them in tow dimensional array. But I want to learn how I can get these as string line and save the values in numeric array.

Thanks very much,
Yours

>>But i please say me can i iterate between characters in a string line.
Considering the format of the data file that statement makes no sense at all.

>>But I want to learn how I can get these as string line and save the values in numeric array.

So you want to read the data one line at a time into a string, then split the string into individual words so that they can be converted to numberic and put into an array ??

use fgets() to read each line then strtok() to extract the individual numbers (words)

char line[255];
float array[255] = {0};
int i = 0;
while( fgets(line, sizeof(line), fp) != NULL)
{
     char *ptr = strtok(line," ");
     while( ptr != NULL)
     {
           array[i] = atof(ptr);
           i++;
           ptr = strtok(NULL, " ");
      }
}

use fgets() to read each line then strtok() to extract the individual numbers (words)

char line[255];
float array[255] = {0};
int i = 0;
while( fgets(line, sizeof(line), fp) != NULL)
{
     char *ptr = strtok(line," ");
     while( ptr != NULL)
     {
           array[i] = atof(ptr);
           i++;
           ptr = strtok(NULL, " ");
      }
}

Thanks very much that is the case. But when i run this snippet i get an warning that 19 " initialization makes pointer from integer without a cast" on lines that use the ptr what is the cause of this warning.
I use DEV C++ for compiling.

Thanks very much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.