Arrays and text files

I need to write a program that reads integer values from a text file and stores them in separate arrays. The contents of the text file is..
1,3,-5
4,-2,-1
(no spaces)

I need to then perform a dot product calculation on the contents of the text file.

The output should look like this...

Please enter the name of the file: inputs.txt
Array 1: 1,3,-5
Array 2: 4,-2,-1
The dot product is: 3

I'm still very new to coding in c++ so any help would be greatly appreciated.
I have started the basic skeleton such as the input command but the more technical parts have me stumped.

Thanks in advance :)
Last edited on
Have you read the numbers into arrays?
Can't figure that out. I've been searching through many sites and forums to see the theory and how it is applied but my lack of knowledge and understanding is making it difficult to do it. So no I havent been able to read the number into the array.
Do you know how to read the numbers into a single variable, printing that variable as you iterate through the file?

And do you know that reading a file is very similar from reading from the standard input?


I have an idea of hw to do it, but I can't get it to work.
I've managed the following code so far...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <fstream>
#include <cstdlib>



using namespace std;



int main()
{

int Array1 [] = {};
int Array2 [] = {};
int  dotProduct;
string file; //inputs.txt


    cout<<"Please enter the name of the file: "<<file;
    cin>>file;


    /*ifstream file ("inputs.txt");
    if (file.is_open())
    {
        int Array1 [3];

        for (int i = 0; i < 3; ++i)
        {
            file>>Array1[i];
        }
    }


    cout<<Array1<<endl;
     */
    return 0;
}

I'm not sure if I've named the arrays correctly but the above is what i've got so far
Last edited on
Please edit your post and add code tags (highlight the code and press the <> icon to add the tags.

First what is the significance of the number 5 that you used for your array sizes? Your sample "file" appears to have either 3 elements (per line) or 6 total elements (3 elements per line and 2 lines).

Next why the global variables? Global variables are a very bad habit, especially when there is only one function. So make those variables local to the function.

Do you realize that you have two variables named Array1? One the global variable the second is in the scope of the if() statement. And because that second variable is local to that if() statement it will go out of scope when the if() statement completes, meaning that after that if() statement all you have left is the first variable which contains all zeros (because it is a global) not the second variable that you used when reading the file.

Lastly (for now) you can't "print" the contents of an array, you need to iterate through the array and print the individual elements of the array.
Oh ok, I'll move the variables and make them local. There were 2 examples in the scope for the assignment and the first one had 5 variables and the second one had 3 variables. So i apologise for the misunderstanding.

The part that is in comments was just me trying to make the file input work, but as you said I have 2 array1's which is silly on my part.

How would I go about getting the file contents to read into the 2 arrays and look like the example at the top ? I'd imagine its probably very simple but I'm not really clued up yet with C++.

Thanks for being patient.
Why do you need two arrays? Looking at your data I would normally use a two dimensional vector to hold that data.

Below is the assignment question. the question wants me to use 2 arrays to make the program.

A dot product is scalar output that is produced by an algebraic operation applied to two
length vectors. In this activity, you are going to create a program that will construct two
arrays of equal length from a text file and then compute the dot product between the two.
For additional reference, see http://mathworld.wolfram.com/DotProduct.html
You need to create a le called dotProduct.cpp for you to test the functionality of
the behaviour you will implement. Finally a make le that you need to provide to compile
and run the program. You are not provided with any test input files and must create your
own as de fined here. Be sure to upload it with the rest of your code. The input text file
you upload should be called inputs.txt.
When the program starts, you will prompt the user to enter a file name such as inputs.txt. This will be structured as follows:

1,2,3,4,5
1,2,3,4,5

It will contain two lines of data, comma separated and consist of integer numbers. The
length of the arrays you need to consider is set to 5. You will read both lines, each into
its own array. From there, you will compute the dot product of these two arrays as well
as display both arrays as they were contained in the text le. Pay close attention to the
use of space and avoid trailing spaces in your output.

If the input file looks like this:

1,3,-5
4,-2,-1

Then an example output is:

Please enter the name of the file: inputs.txt
Array 1: 1,3,-5
Array 2: 4,-2,-1
The dot product is: 3

You will have a maximum of 5 uploads for this activity.
Last edited on
@JonoSnow,
I think you should go back and READ YOUR POST of the assignment. Yes, READ it! Check that it makes grammatical sense and there aren't words (or worse, parts of words) missing.

Then have a check to see if it is consistent. First you say
The length of the arrays you need to consider is set to 5.
Then you proceed to give an example where the length is patently 3!
1,3,-5
4,-2,-1

So which is it? Are the vectors of length 3? Are they of length 5? Are they of variable length depending on the input file? Is there some specified maximum length? If this is unclear then ASK YOUR TEACHER. This matters when it comes to reading from file.

What type of arrays do you want to use? Fixed-length arrays? vector<type>? valarray<type>? array<type,N>? If you don't know then ASK YOUR TEACHER.

Are you expected to compute the dot product from first principles using loops? Or use the built-in std::inner_product? Or the valarray operators * and sum()? If you don't know then ASK YOUR TEACHER.

When it is clear exactly what you are doing ... and you provide more code to give an idea which route have chosen to take ... then it would be a lot easier to advise you.
Last edited on
Mate the most recent post is of what the assignment brief entails, I don't see why the length of the arrays would matter because it can be changed at anytime. I messed up the first post yes but the most recent post explains exactly what needs to be done. I don't see why it's difficult to understand but I apologise for that. I'll go back and fill in all the "file" words because i didn't notice that when I copied the instructions that it pasted them as "le" and not "file".

The word vector is being used in the maths context not the programming context. I asked my teacher about that because it was confusing.

I would add more code but as I stated many times, I'm new to coding and need help. So sorry but I can't add more code at this stage.

So can someone help me ?
Last edited on
So did your teacher clarify that the "maximum" size of the array will 5 ints?

As far as reading the file it appears that you haven't even given it much of a try. You still haven't demonstrated that you know how to read a file into a single variable, printing that variable after each read.

Since it looks like the file will contain two lines you will probably need at least two loops one to read the first line and one to read the second line.

I'll use 3 for the maximum size of the array because then I have an example to compare my output to.

Would I use ifstream or ofstream to open the file. I'm currently working to try and write the code. When I have more I'll post what I have.
Last edited on
This is what I've managed to make. The output each time is 0.
the text folder looks like so...
1,3,-5
4,-2,-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{

    int Array1 =3;
    int Array2 =3;
    int numbers[Array1];
    int numbers2[Array2];
    int count = 0;
    int  dotProduct;
    string inputsFile; //inputs.txt


    cout<<"Please enter the name of the file: "<<inputsFile;
    cin>>inputsFile;



    ifstream inputFile;
    inputFile.open("inputs.txt");
    while (count < Array1 && inputFile >> numbers[count])
        count++;

    inputFile.close();

    cout<<"Array 1:  ";
    for (count = 0; count < Array1; count++)
        {
            cout<<numbers[count]<<" ";
    }

    while (count < Array1 && inputFile >> numbers[count])
        count++;

   cout<<endl;

    cout<<"Array 2:  ";
    for (count = 0; count < Array2; count++)
    {
        cout<<numbers2[count]<<" ";
    }

    inputFile.close();

    cout<<endl;

    dotProduct= (Array1,Array1 + sizeof(Array1) / sizeof(Array1),Array2 , 0);
    cout<<"The dot product is: "<<dotProduct<<endl;

    return 0;
}


Not sure where my issue is.
You need to reinitialize count to 0 before the while loop on line 37 above.
1
2
3
4
    int Array1 =3;
    int Array2 =3;
    int numbers[Array1];
    int numbers2[Array2];

Strictly, this is illegal in C++, as Array1 and Array2 are not const. Some compilers may let you get away with it. ("Array1" and "Array2" are not clever names for what the variables represent, either.)



1
2
3
4
    cout<<"Please enter the name of the file: "<<inputsFile;
    cin>>inputsFile;
    ifstream inputFile;
    inputFile.open("inputs.txt");

Why do you ask for the name of the input file if you are going to ignore it anyway?



1
2
    while (count < Array1 && inputFile >> numbers[count])
        count++;

Well, you might get away with this if the file contained only space-separated numbers. But it doesn't: there are commas (single chars) between those numbers. How are you going to negotiate those? This is one of your biggest problems.


Lines 37 and 38
1
2
while (count < Array1 && inputFile >> numbers[count])
        count++;

Well, you are trying to read into the same array again. And you are beyond array bounds as well, since count will not have a sensible value here. This is a second big problem.



dotProduct= (Array1,Array1 + sizeof(Array1) / sizeof(Array1),Array2 , 0);
Sorry, but this line is complete nonsense. You appear to have cut random snippets of code from goodness knows where and hoped that they stuck together. They don't.



May I suggest that you have a look at the excellent tutorial on this site about reading from files:
http://www.cplusplus.com/doc/tutorial/files/
and also the one on arrays:
http://www.cplusplus.com/doc/tutorial/arrays/


Reading integers into an array while ignoring commas and possibly spaces is not as trivial as I initially thought...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Fills an outgoing array with integers found in the line.
// Carefully ignores commas and spaces during formatted read.
void PopulateArray(const string& line, int* arr, int size)
{
    istringstream iss(line);
    while (iss.peek()==',' || iss.peek()==' ')
        iss.ignore();
    
    int i = 0;
    while (i<size && iss >> arr[i])
    {
        while (iss.peek()==',' || iss.peek()==' ')
            iss.ignore();

        ++i;
    }
}


Was initially much simpler until I started messing while "files" that looked like
,,,,,,  -107,, ,,, 423,,-16
4,-2,-1


#edgecases
Thank you all for your responses. The program itself looks so simple when looking at the output but is actually trickier than I thought. I'll go back and see what needs fixing and hopefully I can get at least something to work.

I really appreciate the help.
Topic archived. No new replies allowed.