0

I'm new to c++ and need help getting numbers from a text file and multiplying them. I'm able to display the text but I don't know how to retrieve the numbers from the text file in order for me to multiply them. ( the input.txt file is just a file that has random names associated with numbers. I want to get the numbers from the text so I can multiply them).Thank you.

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

int main () {
    string line;
    ifstream myfile ("input.txt");
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            cout << line << '\n';
        }
        myfile.close();
    }
    else
        cout << "Unable to open file";
    system("pause");
    return 0;
} 
3
  • 2
    Show us the text file. Commented Jul 15, 2014 at 22:53
  • What does your text file look like? If there is a pattern like name-number-newline etc, you can read in each 'word' (or number) separately, and then only use the numbers. Commented Jul 15, 2014 at 22:54
  • @MohammadAliBaydoun the text file reads as Steven 10 5 Mo 2 8 Ali 45 3 Joe 34 1 I have to get the numbers from the text file and multiply them (an example output will have to be Steven 10*5=50 , Mo 2*8=16 and so on.) Commented Jul 15, 2014 at 23:00

2 Answers 2

1

Lets say that you file looks like this:

Casey 5.3
Ricardo 6.8
...

Then after you getline you can simply do this:

string name;
float grade;    
stringstream ss;
ss.str(line);
ss >> name >> grade;

and grade will contain the number that you seek.

Sign up to request clarification or add additional context in comments.

Comments

0
Steven  10  5
Moe      2  8
Ali     45  3
Joe     34  1

This is what your text file looks like.
You can use operator >> directly and read it all.

std::ifstream file("input.txt");
std::string name;

// This will loop until we can no longer 
// extract names from the file.
while (file >> name) {
    int a;
    int b;

    file >> a >> b;
    std::cout << name << ' ' << a * b << '\n';
}

1 Comment

you made it clear for me to understand! I appreciate your input.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.