user320950
user320950

Reputation: 187

read numbers from files in columns, one column whole numbers, other column numbers with decimals

int price=' ';   // attempt to grab a decimal number - but not the correct way
int itemnum=' '; // attempt to grab a whole number - but not the right way

while((price== (price*1.00)) && (itemnum == (itemnum*1)))

What is a way to get numbers in 2 diff columns where one column is whole numbers and the other are numbers with decimal places?

Upvotes: 0

Views: 3575

Answers (2)

Mike Webb
Mike Webb

Reputation: 9013

The best way would be to get each separately. If it is from a file then you can do this:

int itemnum;
double price;

inputFile >> itemNum >> price; //If the columns are ItemNumber then Price

or

inputFile >> price >> itemnum; //If the columns are the other way around

The >> operator is nice in C++ because it attempts to cast the input to whatever type you are using.

EDIT: Here is a small example for a file:

#include <fstream>
#include <iostream>

int main()
{
    int input1;
    double input2;

    //Open file
    std::ifstream inFile;
    inFile.open("myFile.txt"); //or whatever the file name is

    while(!inFile.eof())
    {
        //Get input
        inFile >> input1 >> input2;

        //Print input
        std::cout << input1 << " " << input2 << " ";
    }

    //Close file
    inFile.close();

    return 0;
}

The file for this could have this data: 120 12.956 121 13.001 1402 12345.8

and the output would be: 120 12.956 121 13.001 1402 12345.8

It will work if the numbers are in columns too.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 754820

You will need to store the price in a float or double (or long double).

Since you are using C++, you should probably be using the '>>' operators to read the values.

Upvotes: 0

Related Questions