简体   繁体   中英

How to get doubles from text c++

I have a text document which looks something like this:

user_name1 1.575
user_name2 3.636
user_name3 2.647
user_name4 5.532
user_name5 4.253

What i am trying to do is, to get these numbers from .txt file into console and save them as variables. I know how to read .txt file in console and I found some answers here how to get each line separately as strings, but i can't get these doubles. Is there some kind of function or whatsoever that goes through strings and finds numbers?

I tried with this:

1) get string of each line 2) loop through them and check ASCII code and if it is a number I saved next 3 or 4 charachters

But its not working very well. Thanks for your help in advance.

EDIT:

string line;

ifstream banka ("banka.txt");

double numbers[5];
if(banka.is_open()) {
    for(int i=0; i<5; i++) {
        getline(cin,line);
        size_t space=line.find(' ');
        string numStr=line.substr(space+1);
        double num = stod(numStr);
        numbers[i]=num;

    }
    banka.close();
}
else {
    cout<<"Unable to open file."<<endl;
}

Why not simply this ?

std::ifstream fin("input.txt");
std::string str;
double num;

while (fin >> str >> num)
{

    std::cout << str << " :" << num <<std::endl;
}

This:

std::string ln; // line
while (std::getline(std::cin, ln)) {
    std::size_t space = ln.find(' ');
    std::string nameStr = ln.substr(0, space);
    std::string numStr = ln.substr(space + 1);
    double num = std::stod(numStr);
}

If you know the line contains one space and only one space:

string dstr = line.substr(line.find(' ')+1);
double d = strtod(dstr.c_str(), NULL);

You can use std::istringstream to parse a string:

std::istringstream iss("user_name1 1.575");
std::string str;
double d;
iss >> str >> d;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM