未知类型的 CIN >>函数模板参数

cin >> function template arg of unknown type

本文关键字:gt 函数模板 参数 类型 未知 CIN      更新时间:2023-10-16

>我有一个函数模板和主要如下:

 template <class type > type* calculate(type inputVal) {
       type val;
       static int counter = 0;
       static type sum = inputVal;
       static type average = inputVal;
       static type* address = &sum
       do {
          cout << "Enter value: ";
          cin >> val;
          counter++;
          sum += val;
          average = sum / counter;
       } while (!cin.eof());
      return address;
 }
void main() {
      int num;
      cout << "Enter Value: ";
      cin >> num;
      int *ptr = calculate(num);
      cout << "SUM: " << *ptr << " AVG: " << *(ptr+1);
 }

我的问题是这应该适用于不同的输入类型而不仅仅是 int,因此如果用户首先输入浮点数,它会将所有内容视为该类型,就像用户输入字符一样。

此外,模板函数无法打印结束值。

普通

变量sum被视为指针算术的单元素数组(N3337 5.7 加法运算符),当ptr指向它时,ptr+1不指向有效对象,因此不得取消引用。如果需要连续内存区域,请使用数组。

另请注意

  • 在更新sumaverage后检查!cin.eof()似乎不是一个好主意,因为它将使用无效(重复)的数据。在处理数据之前检查输入是否成功。
  • 在全局命名空间中声明void main()(或返回类型不是 int main)在标准C++中是非法的。除非你有一些特殊的原因——例如,你的老板或老师禁止编写符合标准的代码——否则你应该使用int main()(在这种情况下)。
  • 您应该将counter初始化为1以将inputVal放入数字中。避免将输入作为参数以避免编写重复代码似乎更好。

试试这个:

#include <iostream>
using std::cin;
using std::cout;
template <class type > type* calculate(type inputVal) {
  type val;
  static int counter = 1;
  static type buffer[2];
  type& sum=buffer[0];
  type& average=buffer[1];
  sum=average=inputVal;
  static type* address = buffer;
  for(;;) {
    cout << "Enter value: ";
    if(!(cin >> val)) break;
    counter++;
    sum += val;
    average = sum / counter;
  }
  return address;
}
int main() {
  int num;
  cout << "Enter Value: ";
  cin >> num;
  int *ptr = calculate(num);
  cout << "SUM: " << *ptr << " AVG: " << *(ptr+1);
}

或者没有参数输入:

#include <iostream>
using std::cin;
using std::cout;
template <class type > type* calculate() {
  type val;
  static int counter = 0;
  static type buffer[2];
  type& sum=buffer[0];
  type& average=buffer[1];
  sum=0; // the type used has to be capable to be converted from integer 0
  average = 0;
  static type* address = buffer;
  for(;;) {
    cout << "Enter value: ";
    if(!(cin >> val)) break;
    counter++;
    sum += val;
    average = sum / counter;
  }
  return address;
}
int main() {
  int *ptr = calculate<int>();
  cout << "SUM: " << *ptr << " AVG: " << *(ptr+1);
}