Repeated Values

Hello all, and thank you for taking the time to help me with this.

I am relatively new to C++ programming and am in need of some help.

I have a text file containing 2 columns of data. I would like to write a program to look at the file and check to see if any of the values in the first column repeat. If they do, then it should sum up the corresponding second column.

for example the text file may look like this:

1 2
2 1
3 1
4 5
3 2
4 1
5 6
15 1

I want the program to output:
1 2
2 1
3 3
4 6
5 6
15 1

I can read the data in using the following snippet of code;

FILE * inFile = fopen(data, "r");
do{
fscanf_s(inFile, "%f%f%d", &first,&second);

/* this is the part where I am lost
if first = any previous value then sum all of those values = secondsum
if first is the only one of its kind then secondsum = second
*/

outFile11 << first << "\t" << secondsum << endl;
outFile11.flush();

ct3++;
count3 = ct3;
}while (ct3 < numberofdatapoints);

thank you again
The values are integers, so you should read them into ints. Forget scanf functions, they're best avoided, use C++ streams instead.

Read the values as follows:
i
1
2
3
4
5
6
nt key, value;
std::ifstream is(filename);
while (is >> key >> value)
{
    // process numbers
}
Well, thank you kbw for the quick response, sorry for my delay.

I will be sure to use that, but it does not help me with the question of how to process the numbers.

I am still confused in how I will be able to obtain my desired output.
Have you heard of a dictionary data structure? It may be suited to your task.
http://www.cs.umd.edu/class/spring2004/cmsc420/sp04-part2v2/node4.html
http://www.itl.nist.gov/div897/sqg/dads/HTML/dictionary.html

The C++ Standard Template Library provides a dictionary, it's called std::map.
Topic archived. No new replies allowed.