473,320 Members | 2,094 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Creating Arrays with files...

I have the numbers 1 through 50 in one line on a text file, in random order. I am trying to read that text file into an array, so as to copy the array and sort it. I can copy and sort arrays fine, and have looked in the forum and found some help, in thread number 598838 but I don't understand these instructions from Ganon11. I understand the creation of the array to max_size, but not sure what Ganon11 meant by "open your ifstream variable to the input file."

I can read a file and print it's contents:

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <stdio.h>
  3.  
  4. int main()
  5. {
  6.   FILE *in;
  7.   char c;
  8.  
  9.   in = fopen("filename.txt", "r");
  10.   if(in != NULL)
  11.   {
  12.  
  13.         printf("The Text Of The File Reads: \n\n\t");
  14.     while((c = fgetc(in)) != EOF) putchar(c);
  15.  
  16.  
  17.  
  18.  
  19.     fclose(in);
  20.  
  21.   }
  22.  
  23.   else printf("Unable to open file");
  24.  
  25.     getchar();
  26.  
  27.   return 0;
  28. }
  29.  
  30.  
But so far as getting those contents to an array, in plain C, I have had no luck. Do I need to have the numbers 1 through 50 on separate lines, or is it alright I have them all on one line as: 22,24,1,13...etc. Working with arrays is alright, but I have to get it into an array first. Thank you in advance!
Sep 22 '07 #1
10 2491
Savage
1,764 Expert 1GB
I have the numbers 1 through 50 in one line on a text file, in random order. I am trying to read that text file into an array, so as to copy the array and sort it. I can copy and sort arrays fine, and have looked in the forum and found some help, in thread number 598838 but I don't understand these instructions from Ganon11. I understand the creation of the array to max_size, but not sure what Ganon11 meant by "open your ifstream variable to the input file."

I can read a file and print it's contents:

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <stdio.h>
  3.  
  4. int main()
  5. {
  6.   FILE *in;
  7.   char c;
  8.  
  9.   in = fopen("filename.txt", "r");
  10.   if(in != NULL)
  11.   {
  12.  
  13.         printf("The Text Of The File Reads: \n\n\t");
  14.     while((c = fgetc(in)) != EOF) putchar(c);
  15.  
  16.  
  17.  
  18.  
  19.     fclose(in);
  20.  
  21.   }
  22.  
  23.   else printf("Unable to open file");
  24.  
  25.     getchar();
  26.  
  27.   return 0;
  28. }
  29.  
  30.  
But so far as getting those contents to an array, I have had no luck. Do I need to have the numbers 1 through 50 on separate lines, or is it alright I have them all on one line as: 22,24,1,13...etc. Working with arrays is alright, but I have to get it into an array first. Thank you in advance!
What Gannon said is:create a variable of ifstream type:

ifstream istr;

and open your variable to a input file means:

istr.open("inputfile");

Now you can read those numbers using >> operator,multiple elements can exist on a single line,just make sure they are separated by a space.

istr>>a;

Savage
Sep 22 '07 #2
Ganon11
3,652 Expert 2GB
Of course, I was operating under the assumption that you were using C++ (which I tend to do :O). If you're using C, you need to use a FILE*, which it appears you are using.
Sep 22 '07 #3
What Gannon said is:create a variable of ifstream type:

ifstream istr;

and open your variable to a input file means:

istr.open("inputfile");

Now you can read those numbers using >> operator,multiple elements can exist on a single line,just make sure they are separated by a space.

istr>>a;

Savage
So even though it is numbers, it needs to be looked at as a string? As well, since I am working in plain C, once I have found out if the character I am looking at is indeed a "number" and not a space, I don't see how to "grab the number" and place it in an array, as istr.open works in C++. Sorry if this is a simple question, I have used Java at my job for five years and now am required to teach myself C. They are very similar, but these slight differences are messing me up. Thanks again.

Fmsguy06
Sep 22 '07 #4
Savage
1,764 Expert 1GB
So even though it is numbers, it needs to be looked at as a string? As well, since I am working in plain C, once I have found out if the character I am looking at is indeed a "number" and not a space, I don't see how to "grab the number" and place it in an array, as istr.open works in C++. Sorry if this is a simple question, I have used Java at my job for five years and now am required to teach myself C. They are very similar, but these slight differences are messing me up. Thanks again.

Fmsguy06
Use fgets instead of fgetc to read a whole line,then parse the line and use atoi to convert it to int array.

Savage
Sep 22 '07 #5
I used fgets and atio, but I believe I am using them wrong:


#include <stdio.h>


//#include <stdlib.h> atio needs this to operate, yet when included I recieve:

//(18): error #2140: Type error in argument 1 to '__stoul'; found 'struct FILE *' //expected 'const char *'.

// If <stdlib.h> left out, output is:
//The Text Of The File Reads: 1 4 6 77 89 4
// "When converted to array is: 4225944


int main()
{
FILE *in;
char c;

in = fopen("test.txt", "r");
if(in != NULL)
{

printf("The Text Of The File Reads: \n\n\t");
while((c = fgetc(in)) != EOF) putchar(c);


//I think I need to parse the line here...
//As well, I tried with the line already parsed, to no avail

printf("\n\n\tConverted to an array is: %d.\n\n"), atoi(in);



fclose(in);

}

else printf("Unable to open file");

getchar();

return 0;
}

So I think the parsing correctly and figuring out why including <stdlib.h> gives me that error are my only problems. I liked being able to just .parse in Java, and so far in the books I have read or the websites visited, it's not that easy in C...or am I much more lost than I believe? Thanks again.

Fmsguy06
Sep 23 '07 #6
oler1s
671 Expert 512MB
Aside: please use CODE tags when posting code. It formats the code properly, including preserving indentation. That allows us to properly read and diagnose the code you post. You get more, and more accurate, answers.

You're making it unnecessarily hard on yourself, by parsing character by character. Take in the entire line, then parse it using strtol repeatedly. The logic follows something like (and others should correct my code, please):

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #define BUFSIZE 256 //or whatever you choose
  3.  
  4. int main()
  5. {
  6.     FILE *in;
  7.     char buf[BUFSIZE];
  8.     int num;
  9.     char* strCur;
  10.  
  11.     in = fopen("text.txt", "r");
  12.     if (in != NULL)
  13.     {
  14.         fgets(buf, BUFSIZE, in);
  15.         while (num = strtol(buf, &strCur, 10))
  16.         {
  17.             puts(num); //or store in some existing number array
  18.         }
  19.     }
  20.  
  21.     return 0;
  22. }
  23.  
The two useful functions here are strtol and fgets.

Also read http://c-faq.com/stdio/getcharc.html.
Sep 23 '07 #7
Aside: please use CODE tags when posting code. It formats the code properly, including preserving indentation. That allows us to properly read and diagnose the code you post. You get more, and more accurate, answers.

You're making it unnecessarily hard on yourself, by parsing character by character. Take in the entire line, then parse it using strtol repeatedly. The logic follows something like (and others should correct my code, please):

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #define BUFSIZE 256 //or whatever you choose
  3.  
  4. int main()
  5. {
  6.     FILE *in;
  7.     char buf[BUFSIZE];
  8.     int num;
  9.     char* strCur;
  10.  
  11.     in = fopen("text.txt", "r");
  12.     if (in != NULL)
  13.     {
  14.         fgets(buf, BUFSIZE, in);
  15.         while (num = strtol(buf, &strCur, 10))
  16.         {
  17.             puts(num); //or store in some existing number array
  18.         }
  19.     }
  20.  
  21.     return 0;
  22. }
  23.  
The two useful functions here are strtol and fgets.

Also read http://c-faq.com/stdio/getcharc.html.
Thank you to oler1s for the CODE recommendation. Using the suggested from all others, I have defined my own array called nuMbers, and tried to place the nuMbers from the text file into that array, using fgets, as Savage recomended.

Expand|Select|Wrap|Line Numbers
  1.  
  2.       #include <stdio.h>
  3.       #include <stdlib.h>
  4.  
  5.       #define BUFSIZE 100
  6.  
  7.  
  8.  
  9.       int main()
  10.  
  11.       {
  12.  
  13.           FILE *in;
  14.  
  15.           char buf[BUFSIZE];
  16.  
  17.           int num;
  18.  
  19.     int nuMbers[100];
  20.  
  21.           char* strCur;
  22.  
  23.  
  24.  
  25.           in = fopen("test.txt", "r");
  26.  
  27.           if (in != NULL)
  28.  
  29.           {
  30.  
  31.               fgets(buf, BUFSIZE, in);
  32.  
  33.               while (num = strtol(buf, &strCur, 10))
  34.  
  35.               {
  36.  
  37.                   puts(nuMbers); // error received here.
  38.  
  39.               }
  40.  
  41.           }
  42.  
  43.  
  44.  
  45.           return 0;
  46.  
  47.       }
  48.  
I believe I am missing a line prior to puts, as on the puts line, I am receiving the error of "Type error in argument 1 to 'puts'; found 'int *' expected 'const char *'. " A character is defined, but if put in the place of nuMbers, i,e puts(strCur) or puts(buf), an infinite loop is created, the numbers stored in the text file printed nicely, but infinitely. I have tried placing lines before puts, like defining a new character, but to no avail. If I can't figure this out before work tomorrow morning, I'll learn in time, and I still thank you all for your help, and thanks in advance again!

fmsguy06
Sep 24 '07 #8
ilikepython
844 Expert 512MB
Thank you to oler1s for the CODE recommendation. Using the suggested from all others, I have defined my own array called nuMbers, and tried to place the nuMbers from the text file into that array, using fgets, as Savage recomended.

Expand|Select|Wrap|Line Numbers
  1.  
  2.       #include <stdio.h>
  3.       #include <stdlib.h>
  4.  
  5.       #define BUFSIZE 100
  6.  
  7.  
  8.  
  9.       int main()
  10.  
  11.       {
  12.  
  13.           FILE *in;
  14.  
  15.           char buf[BUFSIZE];
  16.  
  17.           int num;
  18.  
  19.     int nuMbers[100];
  20.  
  21.           char* strCur;
  22.  
  23.  
  24.  
  25.           in = fopen("test.txt", "r");
  26.  
  27.           if (in != NULL)
  28.  
  29.           {
  30.  
  31.               fgets(buf, BUFSIZE, in);
  32.  
  33.               while (num = strtol(buf, &strCur, 10))
  34.  
  35.               {
  36.  
  37.                   puts(nuMbers); // error received here.
  38.  
  39.               }
  40.  
  41.           }
  42.  
  43.  
  44.  
  45.           return 0;
  46.  
  47.       }
  48.  
I believe I am missing a line prior to puts, as on the puts line, I am receiving the error of "Type error in argument 1 to 'puts'; found 'int *' expected 'const char *'. " A character is defined, but if put in the place of nuMbers, i,e puts(strCur) or puts(buf), an infinite loop is created, the numbers stored in the text file printed nicely, but infinitely. I have tried placing lines before puts, like defining a new character, but to no avail. If I can't figure this out before work tomorrow morning, I'll learn in time, and I still thank you all for your help, and thanks in advance again!

fmsguy06
Are you trying to print the array or the number? Why don't you use printf since I think puts only prints C strings? To print an array:
Expand|Select|Wrap|Line Numbers
  1. int x;
  2. for(x = 0; x < arrayLength; x++)
  3. {
  4.     printf("%d", theArray[x]);
  5. }
  6.  
Sep 24 '07 #9
Are you trying to print the array or the number? Why don't you use printf since I think puts only prints C strings? To print an array:
Expand|Select|Wrap|Line Numbers
  1. int x;
  2. for(x = 0; x < arrayLength; x++)
  3. {
  4.     printf("%d", theArray[x]);
  5. }
  6.  
Am trying to print the array once the array is created, by reading from a file. I tried another idea:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   FILE *fp; //creating file pointer
  6.  
  7.     int nummbers[50];
  8.  
  9.     int counter = 0;
  10.  
  11.     fp = fopen("test.txt", "r"); //opening test.txt
  12.  
  13.     while(!feof(fp)) //while not end of file, keep going
  14.     {
  15.     fscanf(fp, "%i", &nummbers[counter++]);
  16.  
  17. /*getting the numbers from the text file and placing them in an array. I am not sure about this line and think it's what's causing the problem. */
  18.  
  19.     }
  20.     fclose(fp); //closing the file.
  21.  
  22.     printf("Array is %d: ", nummbers[0]); 
  23.     return 0;
  24. }
  25.  
  26.  
  27.  
but this just crashes the compiler without even giving me an error in the code. I thought I was finally understanding, looks like I was wrong again...

Thank again

fmsguy06
Sep 24 '07 #10
Figured it out:

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include "stdafx.h"
  3.  
  4.  
  5. #include <stdio.h>
  6.  
  7. int main()
  8. {
  9.   FILE *fp;
  10.  
  11.     int nummbers[51];
  12.  
  13.     int counter = 0;
  14.  
  15.     fp = fopen("test.txt", "r");
  16.  
  17.     while(!feof(fp))
  18.     {
  19.     fscanf(fp, "%i", &nummbers[counter++]);
  20.     }
  21.     fclose(fp);
  22.  
  23.  
  24.     int g = 0;
  25.     int f = 0;
  26.     int totals = 0;
  27.  
  28. again:
  29.     while(f <=g+4)
  30.     {
  31.     printf("%d\t", nummbers[f]);
  32.     f++;
  33.  
  34.     }
  35.     while(totals < 9)
  36.     {
  37.         printf(" ");
  38.         totals++;
  39.         g = g + 5;
  40.         int f = g+1;
  41.         goto again;
  42.     }
  43.     getchar();
  44.     return 0;
  45.  
  46. }
  47.  
  48.  
That took a while for me to figure out, but couldn't have done it without ya'lls help and I thank you all!

Fmsguy06
Sep 25 '07 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

13
by: muser | last post by:
for the following code: strncpy(temp_issue, &temp1, 4); files.rec1.issue_rec = atol(temp_issue); cout<<files.rec1.issue_rec<<endl; on execution I get the following. 0x0fd10 a memory...
7
by: Kieran Simkin | last post by:
I have in my project in main.c a number of arrays defined like this (outside of any functions): char muser, mpass; I'm declaring them in a number of other .c files (inside functions) like this:...
5
by: JezB | last post by:
What's the easiest way to concatenate arrays ? For example, I want a list of files that match one of 3 search patterns, so I need something like DirectoryInfo ld = new DirectoryInfo(searchDir);...
2
by: David | last post by:
Hi all, I am fairly new to C#. so go easy on me :-) Anyhow, I have a class file that I have set up properties and a method. I am calling this class file directly from and aspx.cs file. So...
10
by: David Fort | last post by:
Hi, I'm upgrading a VB6 app to VB.net and I'm having a problem with a call to a function provided in a DLL. The function takes the address of a structure which it will fill in with values. I...
41
by: Rene Nyffenegger | last post by:
Hello everyone. I am not fluent in JavaScript, so I might overlook the obvious. But in all other programming languages that I know and that have associative arrays, or hashes, the elements in...
3
by: creator_bob | last post by:
How do I create an array of datarows from a sorted list? I put a bunch of datarows into a sorted list to sort them. Then I got an array of the sorted elements. However, I cannot typecast them. ...
2
by: Aryan | last post by:
Hi, I am using C# with framework 2.0 and creating PDF files on-fly, along with this I am using Windows 2003 Server. I am using Byte to take the data input and then save into pdf format on...
5
by: Chandra | last post by:
Hi, I have three files in which i am using 10 arrays each of size( say about 600 i.e A1,A2 ......A10). I am having some memory issues so i want to make use of the memory in a appropraite way....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.