程序中模板类型的输入打印错误
Inputs are printed wrongly of template types in program
这是我的程序与模板的代码片段。它没有错误,但是当我打印时,它会产生错误的结果。请告诉我哪里错了,我该如何解决这个问题。下面是具有三个函数和一个带有模板 T 的主函数的C++代码。
#include<iostream>
using namespace std;
template<typename T>
void input(T* &start, int size){
start = new T[size];
T* beyond = &start[size];
while(start != beyond){
cout<<"nEnter: ";
cin>>*start;
start++;
}
}
template<typename T>
void sort(T* start, int size){
T hold;
for(int j=0; j<size-1; j++){
for(int i=0; i<size-1; i++){
if(start[i]>start[i+1]){
hold=start[i];
start[i]=start[i+1];
start[i+1]=hold;
}
}
}
}
template<typename T>
void display(T* start, int size){
T* beyond = &start[size];
cout<<"nAfter Sorting: "<<endl;
while(start != beyond){
cout<<*start<<"t";
start++;
}
}
int main(){
int* x=NULL;
float* y=NULL;
char* z=NULL;
int size;
cout<<"Enter the number of elements: ";
cin>>size;
cout<<"nEnter integer values:";
input<int>(x, size);
sort<int>(x, size);
display<int>(x, size);
/**
cout<<"nEnter floating values:";
input<float, int>(y, size);
sort<float, int>(y, size);
display<float, int>(y, size);
cout<<"nEnter character values:";
input<char, int>(z, size);
sort<char, int>(z, size);
display<char, int>(z, size);
*/
system("pause");
}
在input
函数中,您分配内存并将其置于start
。然后,将该指针移动到末尾,该结束值将返回到调用函数。然后,您尝试将其用作其他方法的开始,这将导致未定义的行为。
template<typename T>
void input(T* &start, int size){
start = new T[size]; // points to the start
T* beyond = &start[size];
while(start != beyond){
cout<<"nEnter: ";
cin>>*start;
start++; // Moving all the time...
}
// In the end start points to beyond and main gets that as a result
}
如果你真的想玩指针,你可以很容易地修复它:
template<typename T>
void input(T* &start, int size){
start = new T[size];
T* beyond = &start[size];
T* curr = start;
while(curr != beyond){
cout<<"nEnter: ";
cin>>*curr;
curr++;
}
}
这样,start
指针将始终指向开头,并正确返回到调用函数。
在调试器中逐步运行将很容易显示此问题。另外,请始终描述问题,如果您不解释正确的结果是什么或您得到的结果,我们不知道"生成错误的结果"是什么意思,而是使用某些输入。
你可以这样做:
template<typename T>
void input(T* &start, int size){
start = new T[size];
//T* beyond = &start[size-1];
//while(start <= beyond){
for(int i=0;i<size;i++){
cout<<"nEnter: ";
cin>>start[i];
//start++;
}
//}
}
和:
template<typename T>
void display(T* start, int size){
//T* beyond = &start[size-1];
cout<<"nAfter Sorting: "<<endl;
for(int i=0;i<size;i++){
cout<<start[i]<<"t";
}
}
这是一种更简单的形式,可以做你想做的事情,并且有效。
相关文章:
- 打印时有二叉树问题.用户输入不打印任何内容
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 我要求用户输入大小和数组,但是当我打印矢量时,它仅显示'0'作为输出
- 如何打印不带空格的输入整数?
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 使用用户输入打印 6X10 矩阵的代码 - C++
- 如何使用打印到 PDF 打印机在 MFC 和 CView 中以编程方式打印而不提示输入文件名?
- :CIN 不断打印用户在每次循环后输入的内容
- 读取一组用户输入,按升序排序,然后打印结果
- 从用户那里获得无限量的输入,而不是打印最大的3个,而不使用数组
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 使用 getline 从输入文件打印时如何忽略空白行
- 如何打印输入值
- 如何在没有打印语句的情况下报告用户输入错误
- 当我们声明 cin 为 int 并从 cin 中获取输入并在 cout 中打印 cin 时会发生什么?
- 如何通过输入十进制数打印UTF-8符号?
- 为什么如果我从键盘输入EOF克里昂不要在运行窗口打印程序的输出?
- CLion 会自动从标准输入打印回输入,是否有任何解决方法
- 程序中模板类型的输入打印错误
- 下面的代码应该为4和0的输入打印120.000000。但它只显示 120。为什么?以及如何获得所需的输出?