0

I am trying to make my array have a size of a non-constant value. The size should be defined by the "test.txt" file that gets the information from. For example, if the txt file has 10 numbers then the array should be in size of 10. I tried using vectors but I couldn't make it work. Any help would be much appreciated. Here is the code below:

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<cstdlib>

using namespace std;

/* Function to print an array
A int[]: an array of n element
n int; length of an array
*/
void displayList(float A[], int n)
{
int i;
for (i = 0; i < n; i++)
    cout << A[i] << ", ";
    cout << endl;
}

/*
  Insertion Sort function
  A int[]: an array of n element
  n int; length of an array
*/
void insertionSort(float A[], int n)
{
int i, j;
float key;
for (i = 1; i < n; i++)
{
    key = A[i];// take key  
    j = i - 1;

    /* Move elements of arr[0..i-1], that are
    greater than key, to one position ahead
    of their current position */
    while (j >= 0 && A[j] > key)
    {
        A[j + 1] = A[j]; // move element to next postion 
        j = j - 1;  // reduce index of j - go backward in the array
    }
    std::cout << "Step key at i = " << i << ": [" << key << "] inserted at j = " << j + 1 << "                         
   position -> ";
    A[j + 1] = key;  // at j+1 th position we place the key
    displayList(A, n);
}
 };


ifstream input("test.txt"); //put your program together with thsi file in the same folder.

int main() {
    int const ARRAY_SIZE = 9;
    float A[ARRAY_SIZE];
    string line;
    ifstream inFile;
    int i = 0, cnt = 0;
    float n;

inFile.open("test.txt");

if (!inFile) {
    cout << "Unable to open file";
    exit(1); // terminate with error
}


while (!inFile.eof()) {
    getline(inFile, line);
    n = atof(line.c_str());
    cnt++;
}

int cnt;
cin >> cnt;
vector<float> A(cnt);

inFile.close();
inFile.open("test.txt");

if (!inFile) {
    cout << "Unable to open file";
    exit(1); // terminate with error
}


while (!inFile.eof()) {
    getline(inFile, line);
    n = atof(line.c_str());
    A[cnt++] = n;
}


inFile.close();
n = sizeof(A) / sizeof(A[0]);

cout << "insertionSort: \n";
cout << "Unsorted array:                            ";
displayList(A, n);
insertionSort(A, n);

std::cout << "Sorted array:                              ";
displayList(A, n);

}

sample input from txt file:

12

4

5

9

6

11

0

2

0.5

  • 1
    Prefer `std::vector` than arrays. If you must use an array, then **dynamically allocate** one. Peruse your favorite C++ reference for `operator new` and `delete`. – Thomas Matthews Feb 09 '20 at 19:27
  • `while (!inFile.eof()) {` [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – drescherjm Feb 09 '20 at 19:28
  • Please provide a sample of the input file in your post, as text. You may not need to use `getline`. – Thomas Matthews Feb 09 '20 at 19:29
  • 1
    BTW, the expression `sizeof(A) / sizeof(A[0])` only works for arrays that have capacities declared at compile-time. – Thomas Matthews Feb 09 '20 at 19:30
  • Please provide a [mcve] and focus on saying what exactly you expect and what does not work as you expect. – Werner Henze Feb 09 '20 at 19:34
  • I only see `#include ` in your code but no code where you instantiate a vector. What do you mean when you say you are using vectors? – Werner Henze Feb 09 '20 at 19:36
  • @ThomasMatthews The txt file looks like this: 12 4 5 9 6 11 0 2 0.5 each number in a separate line. – Nikolas Andreou Feb 09 '20 at 19:38
  • @WernerHenze vector v(10); float* p = &v[0]; displayList(A, n); something like this – Nikolas Andreou Feb 09 '20 at 19:40
  • @WernerHenze: Please **edit** your post with a sample input, showing if all numbers are on one line or one number per line. Hard to tell in your comment and important. Also, please don't put code in comments; difficult to read. Edit your post with the code. – Thomas Matthews Feb 09 '20 at 19:47
  • You don't need to use `std::getline` and `std::atof`. Read the input using `operator>>`, e.g. `while (input >> f)`. – Thomas Matthews Feb 09 '20 at 19:59
  • If you want us to help you why your code with `std::vector` does not work you must show that code here. We cannot guess what you might have done wrong. – Werner Henze Feb 09 '20 at 20:03

1 Answers1

0

To make it work with vectors you shouldn't create the vector with a number of elements, like vector<float> v(10);. Create an empty vector and add one value at a time to it.

void display(const std::vector<float>& A) {
    std::cout << "Got " << A.size() << " elements.\n";

    for(float value : A) {
        std::cout << value << '\n';
    }
}

int main() {
    std::vector<float> A;   // an empty vector of floats

    float temp;             // a temporary float to use for extraction
    while(input >> temp) {  // loop while extraction succeeds
        A.push_back(temp);  // save the value at the end of the vector
    }

    display(A);
}
Ted Lyngmo
  • 37,764
  • 5
  • 23
  • 50
  • I tried that out and it works okay finding the number of values. But how will I use this to define the array A? – Nikolas Andreou Feb 09 '20 at 23:32
  • @NikolasAndreou The size of automatic arrays must be known at compile time. You can however allocate them dynamically: `std::unique_ptr A = std::make_unique( size );` - but do you really need to? Why not use the vector as is? A vector has a lot of benefits over such an array. – Ted Lyngmo Feb 10 '20 at 06:48
  • Okay I think now I can make it work, thankyou very much Ted – Nikolas Andreou Feb 10 '20 at 08:35