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

Posted on 2006-05-07
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
    LVL 86

    Expert Comment

    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

    can i solve that without using vectors ?
    LVL 86

    Accepted Solution

    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

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
    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 goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
    The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

    729 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

    Need Help in Real-Time?

    Connect with top rated Experts

    23 Experts available now in Live!

    Get 1:1 Help Now