Hi, I'm reading a line from a text_file.txt

The line looks like:
1#Jonh#Smith#PO Box#4.9#5.0#

The code being used:

fstream file;
 file.open("Tbl_cliente.txt", ios::in); // open a file for input
 file.unsetf(ios::skipws);

getline(file, Cli_nombre, '#');
getline(file, Cli_apellido, '#');
getline(file, Cli_dirr, '#');
file >> Cli_total_compras;
file >> Cli_balance;

But when I look for the content of Cli_balance it is equal to ZERO.

Cli_nombre, Cli_apellido, Cli_dirr are String
Cli_total_compras, Cli_balance are double
Any suggestion?

Edited 6 Years Ago by kako13: n/a

Your file contains one single line.

You are making at least 3 calls to getline()... and then making 2 extraction operations after that.

getline() will return a single line from your file.

your file only contains one line.

I would recommend either making one call to getline() (which will read the entire line at once) or make one extraction operation (since there are no white spaces in your line, it will in this case, also read the entire line at once.)

Once you have read in your single line, you can being parsing your line into individual pieces of data if you desire.

Edited 6 Years Ago by Clinton Portis: n/a

Hi, I'm reading a line from a text_file.txt

The line looks like:
1#Jonh#Smith#PO Box#4.9#5.0#

What did you see in Cli_nombre?

getline() will return a single line from your file.

Up to delimiter. He is calling getline(file, ..., '#');

Edited 6 Years Ago by nezachem: n/a

did you try:

fstream file;
 file.open("Tbl_cliente.txt", ios::in); // open a file for input
 file.unsetf(ios::skipws);

getline(file, Cli_nombre, '#');
getline(file, Cli_apellido, '#');
getline(file, Cli_dirr, '#');
getline(file, Cli_total_compras, '#');
getline(file, Cli_balance, '#');

Programmersbook solution is exactly what you are looking for. Then you can use something like atof() to quickly change the string to a double if you need. Something like:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream file;
    file.open("Tbl_cliente.txt", ios::in); // open a file for input
    file.unsetf(ios::skipws);

    string Cli_nombre,Cli_apellido, Cli_dirr, compress, balance;
    double Cli_total_compress, Cli_balance;

    getline(file, Cli_nombre, '#');
    getline(file, Cli_apellido, '#');
    getline(file, Cli_dirr, '#');
    getline(file, compress, '#');
    getline(file, balance, '#');
    Cli_total_compress = atof(compress.c_str());
    Cli_balance = atof(balance.c_str());
    //file >> Cli_total_compras;
    //file >> Cli_balance;

    cout << Cli_nombre << endl << Cli_apellido << endl << Cli_dirr << endl << Cli_total_compress << endl << Cli_balance << endl;
    return 0;
}
This article has been dead for over six months. Start a new discussion instead.