繁体   English   中英

C ++线到矢量

[英]C++ Line into Vector

哇我今天到处都有问题,如果它们似乎重叠,我道歉,但是每一个问题都会出现另一个问题......因为有一件事情不行......但我应该用别的东西...... ....等等。

无论如何,我有一个文本文件:

6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10

6是第二行中的“浮点数”(3.0,2.5等...)3.0,2.5,-1.5都是一系列浮点数。 6和10只是2个整数。

我有一个矢量

std::vector<double> numbers;

我需要做的就是将第二行放入数字中。 所以现在我有

ifstream myfile (filename.c_str());

我可以简单地只做一个myfile >>来得到第一个值(6)但是我怎样才能把第二行放在我的向量中? 记住我只知道第2行(在这种情况下为6),只知道第2行是多大的。

最后2个数字也不应该在这个向量中,而是两个单独的值。 哪个我可以做myfile >> a >> b。

对于很多问题再次抱歉。 但我一直在寻找各地,并提出错误的问题。

myfile >> numElements;
numbers.resize(numElements);
for (int i = 0; i < numElements; i++) {
    myfile >> numbers[i];
}
myfile >> a >> b;

就像是 :

int count, a, b;
double tmp;
std::vector<double> numbers;
ifstream myfile (filename.c_str());
myfile >> count;
for(int i = 0; i < count; ++i) {
    myfile >> tmp; numbers.push_back(tmp);
}
myfile >> a >> b;

我将从你已经从文件中读到的那一点开始,因为看起来你对它很好。 这是最基本的方法。 我的下面的代码使用非常简单的代码来说明这种方法,可以用来理解它是如何工作的。

  1. 得到你想要在解析到一个行string ,这是line在下面我的代码。
  2. string搜索标记,其中每个标记都由不是数字,小数或负号的任何内容分隔
  3. 对于每个标记,使用stringstream将字符串转换为double
  4. 将转换后的double添加到矢量中

在循环结束时,我还将矢量转储到屏幕上进行检查。

#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
using namespace std;

int main()
{
    string line = "3.0 2.5 -1.5 0.0 1.7 4.0";
    vector<double> doubles;

    string::size_type n_begin = 0;
    string::size_type n_end = line.find_first_not_of("-.0123456789", n_begin);
    while( n_begin != string::npos )
    {
        string cur_token = line.substr(n_begin, n_end-n_begin);
        stringstream ss;
        ss << cur_token;
        double cur_val = 0.0;
        ss >> cur_val;
        doubles.push_back(cur_val);
        // set up the next loop
        if( n_end == string::npos )
            n_begin = n_end = string::npos;
        else
        {
            n_begin = n_end + 1;
            n_end = line.find_first_not_of("-.0123456789", n_begin);
        }
    }

    copy(doubles.begin(), doubles.end(), ostream_iterator<double>(cout, "\n"));
}

你的武器库中有copy_n()吗?

template<class In, class Size, class Out>
Out copy_n(In first, Size n, Out result)
{
    while( n-- ) *result++ = *first++;
    return result;
}

把它放在你可以轻松#include它在其他翻译单位的地方。 这很有用。 像这样使用它来复制你的n浮点值:

copy_n(std::istream_iterator<double>(std::cin),
       n,
       std::back_inserter(v));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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