如何从文本c ++获得双打 [英] How to get doubles from text c++

查看:104
本文介绍了如何从文本c ++获得双打的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文档,看起来像这样:

  user_name1 1.575 
user_name2 3.636
user_name3 2.647
user_name4 5.532
user_name5 4.253

我要做的是,将这些数字从.txt文件获取到控制台并将它们保存为变量。我知道如何读取.txt文件在控制台,我发现一些答案在这里如何获得每行单独作为字符串,但我不能得到这些双打。



我试过这个:



1)获取每行的字符串
2)循环遍历它们并检查ASCII码,如果它是一个数字,我保存下3或4个字符



但是它的工作不是很好。非常感谢您的帮助。

 

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<<无法打开文件。<< endl;
}


解决方案



  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);
}


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;
}

解决方案

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);
}

这篇关于如何从文本c ++获得双打的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆