C++线转化为向量
哇,我今天到处都有问题,如果它们看起来重叠,我很抱歉,但每个问题都会带来另一个问题......因为一件事不起作用......但我应该使用其他东西...... ....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 行有多大。
另外,最后 2 个数字不应该位于该向量中,而是两个单独的值。 我可以做 myfile >>一个>> b.
再次抱歉问了这么多问题。但我实际上已经到处寻找并提出了可能错误的问题。
Wow I've been all over the place with questions today and I apologize if they seem to overlap, but for every question comes another question...Since one thing wont work......but I should use something else......etc.
Anyways, I have a text file:
6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10
6 is the Number of "floats" in the second line (the 3.0,2.5 etc...)
3.0,2.5,-1.5 are all a series of floats.
6 and 10 are just 2 integers.
I have a Vector
std::vector<double> numbers;
All i need to do, is get the Second line put into numbers.
So right now I have
ifstream myfile (filename.c_str());
I can simply just do a myfile>> to get the first value (6)
but how would I go about putting the second line in my vector? Remember I ONLY know how big line 2 is, by reading in the first line (the 6 in this case).
Also the last 2 numbers aren't supposed to be in this vector, but two seperate values.
Which i can just do myfile >> a >> b.
Sorry again for sooo many questions. but I've literally been looking everywhere and asking probably the wrong questions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
类似的东西:
something like :
我将从您已经从文件中读取行的位置开始,因为您似乎对此表示同意。这是最基本的方法。我下面的代码使用非常简单的代码说明了这种方法,可以用来理解它是如何工作的。
字符串
的行,这是我下面代码中的line
。string
中搜索标记,其中每个标记均以非数字、小数或负号的任何内容分隔。double 通过使用
stringstream
。在循环结束时,我还将向量转储到屏幕上以供检查。
I'm going to start from the point where you've already read in the line from the file, since it seems like you're OK with that. This is the most basic approach. My code below illustrates this approach using very straightforward code that could be used to understand how this works.
string
, this isline
in my code below.string
for tokens, where each token is seperated by anything that isn't either a digit, a decimal, or a negative signdouble
by usingstringstream
.At the end of the loop, I also dump the vector to the screen for inspection.
您的武器库中有
copy_n()
吗?将其放在您可以轻松地将其#include到其他翻译单元中的地方。这很有用。像这样使用它来复制
n
个浮点值:Do you have
copy_n()
in your arsenal?Put it somewhere where you can easily #include it in other translation units. It's useful. Use it like so to copy your
n
floating-point values: