我对 C++ 相当陌生,但从逻辑上讲,我认为这应该可行。
我有一个函数,它接受用户的输入来设置数组的内存分配:
void setarraynum(){
string mystr;
cout<<"Please enter the size of your array: ";
getline(cin, mystr);
stringstream(mystr)>>arraynum;
array = new int [arraynum];
cout<<"\n";
}
arraynum 和 array 是全局变量,设置为:
int arraynum;
int * array;
然后我有一个接受数组输入的函数:
void setarray(){
string mystr;
cout<<"Please enter "<<arraynum<<" numbers:\n";
for(int n=0; n<arraynum; n++){
getline(cin, mystr);
stringstream(mystr)>>array[n];
};
cout<<"\n";
}
在输入数组编号时会出现问题,数组的第一个实例 (array[0]) 会自动设置为 0。就好像循环在不询问用户输入的情况下迭代第一次迭代一样。然后它继续像往常一样询问用户。
有任何想法吗?
谢谢。
*编辑(根据要求,整个代码):
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int arraynum;
int * array;
bool isin = false;
int input;
char order;
void insertionsortdesc(int a[]);
void insertionsortasc(int a[]);
void getarray(int a[]);
void isinarray(int a[], int b);
void setsearch();
void setarray();
void setarraynum();
void setorder();
int main(){
cout<<"\n//// INPUT ////\n\n";
setarraynum();
setorder();
setarray();
setsearch();
if(order=='a'){insertionsortasc(array);
}else if(order=='d'){insertionsortdesc(array);};
cout<<"//// OUTPUT ////\n\n";
getarray(array);
isinarray(array, input);
return 0;
}
void setorder(){
bool isvalid = false;
while(!isvalid){
cout<<"Ascending or Descending [a/d]: ";
cin>>order;
if(order=='a'||order=='d'){isvalid = true;
}else{cout<<"Please enter a valid option!\n";};
};
cout<<"\n";
}
void setarraynum(){
string mystr;
cout<<"Please enter the size of your array: ";
getline(cin, mystr);
stringstream(mystr)>>arraynum;
array = new int [arraynum];
cout<<"\n";
}
void setsearch(){
string mystr;
cout<<"Search for (int): ";
getline(cin, mystr);
stringstream(mystr)>>input;
cout<<"\n";
}
void setarray(){
string mystr;
cout<<"Please enter "<<arraynum<<" numbers:\n";
for(int n=0; n<arraynum; n++){
getline(cin, mystr);
stringstream(mystr)>>array[n];
};
cout<<"\n";
}
void insertionsortdesc(int a[]){
for(int n=1; n<arraynum; n++){
int key = a[n];
int j = n-1;
while((j>=0)&&(a[j]<key)){
a[j+1] = a[j];
j -= 1;
};
a[j+1]=key;
}
}
void insertionsortasc(int a[]){
for(int n=1; n<arraynum; n++){
int key = a[n];
int j = n-1;
while((j>=0)&&(a[j]>key)){
a[j+1] = a[j];
j -= 1;
};
a[j+1]=key;
}
}
void isinarray(int a[], int b){
for(int n=0; n<arraynum; n++){
if(a[n] == b){
isin = true;
break;
};
};
if(isin){
cout<<b<<" is present in the given array.";
}else{
cout<<b<<" is not present in the given array.";
};
cout<<"\n\n";
}
void getarray(int a[]){
cout<<"Sorted array sequence: ";
for(int n=0; n<arraynum; n++){
cout<<a[n]<<", ";
};
cout<<"\n\n";
}