我有这个程序,要求用户输入数字,并询问用户是否要查看输入历史记录。所以我想知道我的代码是否正确。我想知道执行cin>>num[count-1]
是否正确,或者是否有正确的方法来获取用户输入的数据。这是:
#include<iostream>
using namespace std;
int main(){
const int size = 20;
int *num = new int[size];
char answer;
int count = 1;
while(true){
cout<<"ENTER NUMBER: \n";
cin>>num[count-1];
cout<<"TRY AGAIN? ";
cin>>answer;
switch(answer){
case 'y':
count++;
system("cls");
break;
default:
cout<<"INPUT HISTORY: \n";
for(int i=0;i<=count-1;i++){
cout<<num[i]<<endl;
}
count++;
}
}
delete [] num;
return 0;
}
我想知道正在执行cin >> num [count-1]`是正确的还是有正确的方法来获取用户输入的数据。
您的代码是C样式的代码。您有std :: array和std :: vector可以帮助您编写更安全和整洁的代码。因为问题中的标签是动态数组,所以我建议使用std :: vector。在下面,您可以检查您的代码是否与替换代码一起使用。
#include <iostream>
#include <vector>
using namespace std;
int main() {
//int *num = new int[size]; //normally you don't need to use new. Let the c++ manage it for you
vector<int> num;
char answer;
while (true) {
cout << "ENTER NUMBER: \n";
num.emplace_back(); //Create a new element to vector num
cin >> num.back(); //set this new element
cout << "TRY AGAIN? ";
cin >> answer;
if (answer == 'y')
system("cls");
else {
cout<<"INPUT HISTORY: \n";
for (auto& numEle : num) //It will interate over all elements of num
cout<< numEle <<endl;
//break; //Maybe you want to break the loop here
}
}
// delete [] num;
return 0;
}