4

哇,我今天到处都是问题,如果它们似乎重叠,我很抱歉,但是对于每个问题都会出现另一个问题......因为一件事不起作用......但我应该使用别的东西...... ....ETC。

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

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) 但我将如何将第二行放入我的向量中?请记住,通过阅读第一行(在本例中为 6),我只知道第 2 行有多大。

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

再次抱歉这么多问题。但我确实一直在到处寻找并提出可能错误的问题。

4

4 回答 4

5
myfile >> numElements;
numbers.resize(numElements);
for (int i = 0; i < numElements; i++) {
    myfile >> numbers[i];
}
myfile >> a >> b;
于 2010-11-29T23:00:31.947 回答
1

就像是 :

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;
于 2010-11-29T23:04:30.760 回答
1

我将从您已经从文件中读取该行的地方开始,因为您似乎对此表示满意。这是最基本的方法。我下面的代码使用非常简单的代码说明了这种方法,可以用来理解它是如何工作的。

  1. 获取要解析的行 a string,这line在我下面的代码中。
  2. 搜索string标记,其中每个标记都由非数字、小数或负号的任何内容分隔
  3. 对于每个标记,double使用. 将字符串转换为 a stringstream
  4. 将转换后的双精度添加到您的向量中

在循环结束时,我还将向量转储到屏幕上以供检查。

#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"));
}
于 2010-11-29T23:16:49.523 回答
1

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));
于 2010-11-30T00:03:15.190 回答