以在未知大小的数组中的C ++ [英] Taking in array of unknown size in c++

查看:165
本文介绍了以在未知大小的数组中的C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我感到非常新的节目,而我正在一个C ++类。基本上,对于当前的项目,我必须采取未知大小的数组,调整其大小,输出一帮平均一样,Q1,Q3,等我有麻烦接受来自用户的阵列中的统计数据。我需要停止服用变量一旦进入0.这是我:

Ok I am extremely new to programming, and I am taking a c++ class. Basically for the current project I have to take in an array of unknown size, resize it, and output a bunch of statistics like average, Q1, Q3, etc. I am having trouble taking in the array from the user. I need to quit taking in variables once they enter 0. Here is what I have:

int i = 1; //When I first posted this I didn't mean to comment out the '= 1' part
do {
    cin >> array[i];
    if (array[i] != 0)
        return true;
} while (true);

我是什么做错了吗?之后,我每次进入1号无论我输入什么号码的程序停止。

What am I doing wrong? the program stops after I enter 1 number every time no matter what number I enter.

我使用向量类顺便说一句。

I am using vector class btw.

推荐答案

执行以下操作:

// change int to your type
int val;
std::vector<int> vec; 
while(std::cin >> val) {
  if(val == 0) break;
  vec.push_back(val);
}

原因:一个陈述return子句将导致退出循环

Reason: Stating a return clause causes to exit the loop.

使用的std ::矢量的保证的任意尺寸的条件。

更新@ nonsensickle的建设性的言论后:

以下code的片也保证了的只有0结束输入过程的条件:

The following piece of code also ensures the only 0 terminates input process condition:

// change int to your type
int val;
std::vector<int> vec; 
do {
  if(std::cin >> val) {
    if(val == 0) break;
    vec.push_back(val);
  } else { // fix broken input stream in case of bad input
    std::cin.clear();
    std::cin.ignore(1,'\n');
  }
} while(true);

和更复杂的方式,虽然矫枉过正,但什么是地狱:),使用模板和类型特点:

and a more sophisticated way, although overkill but what the hell :), with templates and type traits:

template <typename T> 
struct zero_traits
{
  static T getzero() { return T(0); }
};

template <>
struct zero_traits<std::string> 
{
  static std::string getzero() { return "0"; }
};

template <>
struct zero_traits<char> 
{
  static char getzero() { return '0'; }
};

template <typename T>
std::vector<T> read_values()
{
  T val;
  std::vector<T> vec; 
  do {
    if(std::cin >> val) {
      if(val == zero_traits<T>::getzero()) break;
      vec.push_back(val);
    } else {
      std::cin.clear();
      std::cin.ignore(1,'\n');
    }
  } while(true);
  return vec;
}

int main()
{
// change int to your type
std::vector<int> vec = read_values<int>();
for(auto i : vec) std::cout << i << std::endl;
}

这篇关于以在未知大小的数组中的C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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