how to read only  numbers from 2 text files and add them together (c++)

Posted on 2006-05-07
Medium Priority
Last Modified: 2010-04-01
i wand to read only numbers from a txt file like
A   4
B    3
C   2.5
Then from a txt file like
A   3
B   4
C   3

and finally get the result
A  12
B   12
C   (2.5) * 3=7.5
i use c++
thank you
Question by:kriftsi
  • 2
LVL 86

Expert Comment

ID: 16626385
If the input always is identical, you could just

#include <vector>
#include <iostream>
#include <fstream>
using namespace std;

int main () {

  vector <double> v1;
  vector <double> v2;
  int count = 0;

  ifstream f1("file1.txt");
  ifstream f2("file2.txt");

  while (!f1.eof() && !f2.eof()) {

    double d1;
    double d2;
    char letter;

    // skip letters
    f1 >> letter;
    f2 >> letter;

    // read numbers
    f1 >> d1;
    f2 >> d2;

    // store them


  for (int i = 0; i < count; ++i) {

    cout << v1[i] << " * " << v1[i] << " = " << v1[i] * v2[i] << endl;

  return 0;

Author Comment

ID: 16626450
can i solve that without using vectors ?
LVL 86

Accepted Solution

jkr earned 1500 total points
ID: 16626479
Yes, but that would probably be less efficiant - that is, if you don't only have three lines per file. Why would you not want to use vectors? I am asking because I specifically chose them to avoid a collision with EE's 'no homework' rule.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question