Re: dynamic array of ints
From: rossum (rossum48_at_coldmail.com)
Date: 07/30/04
- Next message: Nick Landsberg: "Re: Rework [Was: Static vs. Dynamic typing...]"
- Previous message: John Hanley: "using realloc()"
- In reply to: John Hanley: "dynamic array of ints"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 29 Jul 2004 23:44:16 +0100
On Wed, 28 Jul 2004 12:18:53 -0600, "John Hanley"
<jdhanley@telusplanet.net> wrote:
>I have an interesting problem and I'm not sure the best way to do this.
>
>I am reading in a variable number of integers from a file (eg. 001 002 003
>004 012 015). At compile time I have no idea how many will be there. But I
>need to parse them out and put them in an array.
>
>I could do an fscanf and just read until '\n', however I won't know how many
>are there and thus don't know how large to make my array.
>
>I could read it in as one large string, traverse through and count the
>number of ints and then allocate memory based on that. However I am not
>sure what to use to read the ints from the string. sscanf works but
>multiple calls to it start at the beginning of the string each time. And
>it seems like a sloppy way to do things anyway.
>
>Are there any suggestions as to what approach to take with this? I wanted
>to avoid using a link list as it seems like alot of work for maybe less than
>10 ints I need to parse out.
>
>Suggestions? Ideas?
>Thanks!
>
>
>
You don't say what language(s) you have available. This is a simple
task with a C++ vector.
// Reading a file of integers in C++
#include <vector>
#include <fstream>
#include <iostream>
#include <cstdlib>
main() {
const char* INPUT_FILE_NAME = "file-of-integers.txt";
// Open input file
std::ifstream input_file;
input_file.open(INPUT_FILE_NAME);
if (!input_file) {
std::cerr << "Could not open "
<< INPUT_FILE_NAME
<< " for reading\n";
return EXIT_FAILURE;
} // end if
// Read integers into a vector
std::vector<int> int_vec;
int current_int = 0;
while (input_file >> current_int) {
int_vec.push_back(current_int);
} // end while
// Process integers in vector
for (int i = 0; i < int_vec.size(); ++i) {
if (i > 0) { std::cout << ", "; }
std::cout << int_vec[i];
} // end for
std::cout << std::endl;
return EXIT_SUCCESS;
} // end main()
-------------------------------
file-of-integers.txt
001 002 003 004 012 015 027
-------------------------------
program output:
1, 2, 3, 4, 12, 15, 27
-------------------------------
In order to keep things simple I have done no error checking on the
reading of the file. I don't know how reliable your input file is.
rossum
-- The ultimate truth is that there is no Ultimate Truth
- Next message: Nick Landsberg: "Re: Rework [Was: Static vs. Dynamic typing...]"
- Previous message: John Hanley: "using realloc()"
- In reply to: John Hanley: "dynamic array of ints"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|