cleanplay
cleanplay

Reputation: 291

vector manipulations and storage into a third vector

I am using the following code to store the difference of quantities in two vectors a and b into vector d but it is not working correctly. Can you please tell where is the error ? the input file has text like : 10- number of pairs

8 50   //value in a -space- value in b
74 59
31 73
45 79
24 10
41 66
93 43
88 4
28 30
41 13

The code:

long int x, i = 0, j = 0;
FILE *fp = fopen("jobs.txt", "r");
fscanf(fp, "%lu", &x);
long int c = x;
vector<long int> a;
vector<long int> b;
vector<long int> d;

while (fscanf(fp, "%lu", &x) != EOF)

{
    a.pb(x);
    i++;
    fscanf(fp, "%lu", &x);
    b.pb(x);
    j++;
}

int k = 0;

while (k < c)
{
    d.pb(a[k] - b[k]);
    k++;
}

Upvotes: 0

Views: 85

Answers (3)

I believe the problem is, that you are not handling the whitespace in your scanf() calls. You can easily read your pairs of values using

scanf("\n%lu %lu", &ia, &ib)

or

scanf("%lu %lu\n", &ia, &ib)

depending on whether your want to consume a leading or trailing newline.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227370

Concerning the element-wise vector difference calculation, a simple way to do this is using standard library algorithms such as std::transform and function objects such as std::minus. This example calculates the element-wise difference of two vectors and stores it in a third:

#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>

int main()
{
  std::vector<int> a={10, 10, 10, 10, 10};
  std::vector<int> b={0, 1, 2, 3, 4};
  std::vector<int> c;

  std::transform(a.begin(),
                 a.end(),
                 b.begin(), 
                 std::back_inserter(c),
                 std::minus<int>());

  for (const auto& i : result)
    std::cout << i << " ";
  std::cout << std::endl;
}

Concerning reading pairs of numbers into two vectors, you could consider reading from an std::ifstream.

#include <fstream>
#include <vector>

int main()
{
  std::ifstream fp("jobs.txt");

  int ia, ib;
  while (fp >> ia >> ib)
  {
    a.push_back(ia);
    b.push_back(ib);
  }
}

Upvotes: 1

woggioni
woggioni

Reputation: 1432

I think the problem might be the fact that the first value you read with fscanf is actually discarded, since it is immediately overwritten by a second call to fscanf (the one in the while condition). In this way you will probably read the value in a wrong way comparing the second value of the first couple with the first value of the second and so on.. Just remove the fscanf call on line 3.

Upvotes: 1

Related Questions