我如何采用整数行? [英] How Do I Take In Rows Of Integers?

查看:109
本文介绍了我如何采用整数行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是针对C ++的。

我想按行存储整数,但每行中的数字可能会有所不同。

所以这样的事情不会work:

This is for C++.
I want to store integers by rows and how many numbers are in each row may vary though.
So something like this won't work:

int test[5] = {0};
	for( int i=0; i<5; i++)
		file >> test[i];



我在考虑使用getline,但这需要字符串...



来自文件的输入:


I was thinking of getline but that takes in strings though...

The input from a file:

1 3 250.00 
2 
15 1 1000.00
3 4 300.00

推荐答案



从你给出的输入格式来看,

你将不得不这样做一些文字处理。我的意思是如果你使用getline(),然后在读完一行后,你需要从行中获取单个字符串并将它们转换为整数。它可以完成,你需要自己解决这个问题。



STL conatiner能够帮助你处理存储部分。(什么是STL) [ ^ ]



简单地说,您可以从文本文件中读取输入。

然后使用 std :: map [ ^ ]以及 std :: vector [ ^ ]。

您可以使用的地图是


Looking from the input format you have given,
you will have to do some text processing. I mean if you go with getline(), then after you have read a line, then you need to get the individual strings from the line and convert them to integers. It can be done and you need to figure this part out yourself.

An STL conatiner would be able to help you with the storage part.(what is STL)[^]

Simply put you can read the input from the text file.
Then use a std::map[^] alongwith a std::vector[^].
The map you can use is
std::map<int,std::vector<int>>



所以键存储行中的整数数量,向量将存储实际的整数值。





然后使用迭代器遍历地图而不是原始循环。

这可能会让你免于重新发明轮子



希望这有帮助!!


so the key stores the number of integers in a row and the vector will store the actual integer values.


Then use iterators for traversing through the map instead of raw loops.
This might save you from 're-inventing the wheel'

hope this helps !!


你应该使用动态数组,比如 vector< vector<双> >

假设您的文本文件名是 foo.txt 那么您可能会写这样的内容:

You should use a dynamic array, like a vector <vector <double> >.
Suppose your text file name is foo.txt then you might write something like this:
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main()
{
  string line;
  ifstream ifs("foo.txt");

  vector < vector < double > > md; // dynamic array

  while ( getline(ifs, line).good())
  {
    md.push_back( vector <double >() );
    double d;
    stringstream ss(line);
    while ( ss.good() )
    {
      ss >> d;
      md.back().push_back(d);
    }
  }

  // show the collected items
  for (int r = 0; r < md.size(); ++r)
  {
    for ( int c = 0; c < md[r].size(); ++c)
    {
        cout << md[r][c] << " ";
    }
    cout << endl;
  }
}


这篇关于我如何采用整数行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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