重复一组输入,存储并跟踪每个输入.C++

Repeating a set of inputs, storing and keeping track of each. C++

本文关键字:输入 存储 跟踪 C++ 一组      更新时间:2023-10-16

我希望创建一个程序,向用户提出5个不同的问题。每回答5个问题,程序就会询问用户是否希望输入一组新的答案。

我将使用什么功能来重新运行问题,以及存储和跟踪问题的功能?

string Q1[10];
string Q2[10];
int Q3[10];
int Q4[10];
char newEntry;

do{
for(int i=0; i<11; i++){
cout << "Question 1: " << endl;
cin >> Q1[i];
}
for(int i=0; i<11; i++){
cout << endl << endl << "Question 2: " << endl;
cin >> Q2[i];
}
for(int i=0; i<11; i++){
cout << endl << endl << "Question 3: " << endl;
cin >> Q3[i];
}
for(int i=0; i<11; i++){
cout << endl << endl << "Question 4: " << endl;
cin >> Q4[i];
}
cout << "Would you like to repeat? Enter either 'y' or 'n': " << endl;
cin >> newEntry;
}while (newEntry=='y');



system("pause");
return 0;
}

我建议使用字符串向量来存储答案,而不是使用数组。例如,您的程序可能如下所示:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, const char * argv[])
{
vector<string> Q1;
vector<string> Q2;
vector<string> Q3;
vector<string> Q4;
vector<string> Q5;
char newEntry = '';
string temp;
do {
cout<<"Question 1: "<<endl;
cin>>temp;
Q1.push_back(temp);
temp.clear();
cout<<"Question 2: "<<endl;
cin>>temp;
Q2.push_back(temp);
temp.clear();
cout<<"Question 3: "<<endl;
cin>>temp;
Q3.push_back(temp);
temp.clear();
cout<<"Question 4: "<<endl;
cin>>temp;
Q4.push_back(temp);
temp.clear();
cout<<"Question 5: "<<endl;
cin>>temp;
Q5.push_back(temp);
temp.clear();
cout << "Would you like to repeat? Enter either 'y' or 'n': " << endl;
cin >> newEntry;
} while (newEntry=='y');
return 0;
}

我认为这就是你想要的东西。如果你不熟悉矢量,这里有一个不错的教程/参考资料供你参考。这种方法的优点是,向量将存储基本上与您想要的答案一样多的答案,并且您可以像访问数组一样访问。

至于while循环的问题,它应该可以像我上面展示的那样正常工作。在使用之前,请确保初始化用于存储答案的字符,这样就可以了。

这为您提供了一种存储所有答案的方法。我不确定一旦答案被存储起来,你打算对它们做什么,但如果你想将一个答案与之前的答案进行比较,你需要知道的就是你在while循环的哪个迭代中寻找的答案,以及你正在寻找的问题,你可以找到你的答案。例如:

int index = 0;//i want the answer from the fisrt occurance of the loop.
string answer = Q1[index];//i want the answer to Question 1 from loop occurance 1
index=1;//i want the answer from the second occurance of the loop.
string answer2 = Q1[index];//i want the answer to Question 1 from loop occurance 2
if (answer==answer2) {
cout<<"Answers were the same";
}
else cout<<"Answers were not the same";

我希望我能帮忙,祝你好运!

for循环移出所有问题。

for(int i=0; i<10; i++){
cout << "Question 1: " << endl;
cin >> Q1[i];
cout << endl << endl << "Question 2: " << endl;
cin >> Q2[i];
cout << endl << endl << "Question 3: " << endl;
cin >> Q3[i];
cout << endl << endl << "Question 4: " << endl;
cin >> Q4[i];
cout << "Would you like to repeat? Enter either 'y' or 'n': " << endl;
cin >> newEntry;
if (newEntry != 'y')
break;
}

请注意,循环索引可能只有[0,10)而不是[0,11),因为Q1Q2Q3Q4的大小为10。