C ++如何将字符串逐行转换为double

时间:2018-10-16 06:55:46

标签: c++ arrays string double

我的字符串看起来像这样:

89.800000
89.800000
91.840000
87.760000
60.500000

我需要将其拆分为双数组。

double* data = new double[20];

我需要逐行读取字符串并将其转换为双精度数组。请帮忙。谢谢。

为什么它超出范围?请帮忙。如果是(data.at(i)<最小值)

string vyhodnoceni(string nazev_souboru, double &minimum) { // vyhodnocuje volné místo na disku
    string alarm;
    string s = vypocet2(nazev_souboru);
    string st = s + "\n";
    //cout << st;
    bool dataok = true;
    bool bad = false;

    vector<string>::iterator a;
    istringstream sin(st);
    vector<double> data;
    double next = 0.0;
    while (sin >> next) {
        data.push_back(next);
    }
    process(data);

    for (size_t i = 0; i <= data.max_size(); i++)
    {
        if (data.at(i) < minimum)
        {
            dataok = false;
        }
        else
        {

        }

        if (data.at(i) == 0)
        {
            bad = true;
        }
    }

    if ((vypocet(nazev_souboru) < minimum) || (dataok == false)) {
        alarm = "LDS";
    }
    else alarm = "OK";

    if ((vypocet(nazev_souboru) == 0) || (bad == true)){
        alarm = "UER";
    }

    return alarm;
}

3 个答案:

答案 0 :(得分:4)

如果您的输入来自字符串:

#include <iostream>
#include <sstream>
#include <vector>

void process(const std::vector<double>& data) {
  for (const double x : data) {
    std::cout << x << std::endl;
  }
}

int main() {
  std::string input = "89.800000\n 91.840000";
  std::istringstream sin(input);
  std::vector<double> data;
  double next = 0.0;
  while (sin >> next) {
    data.push_back(next);
  }
  if (!sin.eof()) {
    std::cerr << "Warning: encountered non-double value." << std::endl;
  }
  process(data);
  return 0;
}

如果您的输入来自文件“ input.txt”:

#include <fstream>
#include <vector>

int main() {
  std::ifstream fin("input.txt");
  std::vector<double> data;
  double next = 0.0;
  while (fin >> next) {
    data.push_back(next);
  }
  if (!fin.eof()) {
    std::cerr << "Warning: encountered non-double value." << std::endl;
  }
  process(data);
  return 0;
}

答案 1 :(得分:0)

                istringstream sin(st);
                vector<double> data;
                double next = 0.0;
                bool tecmez = false;
                vector<string> vstr;

                while (sin >> next) {
                    ostringstream strs;
                    strs << next;
                    string str = strs.str();
    data.push_back(next);
}

答案 2 :(得分:0)

首先,您将真正想使用vector而不是数组...我认为您已经在使用它,但是您可以使用istream_iterator使其更加整洁:

vector<double> data { istream_iterator<double>(sin), istream_iterator<double> {} }

对于评估超出范围,您可以使用any_of和lambda或bind语句轻松评估是否有少于minimum的元素,例如:

any_of(cbegin(data), cend(data), bind(less<double>(), placeholder::_1, minimum))

Live Example