[英]Pointers/References in C++ Project
我只學習了幾個月的 C++。 我們有一個關於指針/引用的項目。 這是我提交的下面的代碼。 但是,我的老師說我的代碼中沒有包含指針/引用。 我確信我在第 31-42 行做了。 我在理解指針時遇到問題。 請就我應該做的不同之處提供反饋。
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
//Opening File
ifstream cafefile;
cafefile.open("cafeteria.txt");
//Check for errors
if (!cafefile)
{
cout << "cafeteria.txt did not open properly" << endl;
exit(9999);
}
//String & char
string choice;
string array[4][3];
char out;
//Pointers to the food
string food[] { "Cheese Pizza", "Hamburger", "Fish Sticks", "Mystery Meat" };
string *foodptr {food};
//Set yes & no to 4 array
int yes[4]{ 0 };
int no[4]{ 0 };
//pointer for integer Yes / NO
int* yesptr{ yes };
int* noptr{ no };
//Counters of Likes & Dislikes set = 0
int like = {0};
int dislike = {0};
for (int i = 0; i < 4; i++)
{
//Reopen the file
ifstream file("cafeteria.txt");
while (getline(file, choice))
{
istringstream pick(choice); //istringstream is input stream class, which operates on string
getline(pick, choice, '\t');
if (foodptr[i] == choice)
{
pick >> choice;
if (choice == "Y")
like++; //increment
else if (choice == "N")
dislike++; //increment
}
}
//Setting the yes = like
yesptr[i] = like;
noptr[i] = dislike;
//Set to 0
like = 0;
dislike = 0;
}
for (int m = 0; m < 4; m++)
{
array[m][0] = foodptr[m];
}
for (int j = 0; j < 4; j++)
{
array[j][1] = to_string(yesptr[j]);
}
for (int i = 0; i < 4; i++)
{
array[i][2] = to_string(noptr[i]);
}
//Display of the Program
cout << "School Cafeteria Survey!" << endl;
cout << endl;
cout << "Food Item" << "\t" << "Like" << "\t" << "Dislike" << endl; //Gives the tab space Horizontally in your output
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
cout << array[i][j] << "\t";
}
cout << endl;
}
//Background color, making it unique
system("color 6");
//Exit the Prgram
cout << endl;
cout << "Please enter 'E' to exit!";
cin >> out;
if (out == 'e' || out == 'E')
{
exit(0);
}
system("pause"); //pause the program
return 0;
}
請提供有關我應該解決的問題的解決方案。
如果您動態創建數組會更好,即使用指針動態創建二維數組
string **array;
array = new int *[4];
for(int i=0; i<4; i++){
array[i] = new int[3];
}
除此之外,您的老師一定希望您不使用索引訪問這些數組,而是使用指針和引用。 這意味着您不應該使用yesptr[i]訪問數組,而應該使用*(ysptr + i) 。 因此,例如,如果您處於循環中,請執行以下操作
for (int m = 0; m < 4; m++)
{
*(*(array+m)+0) = *(foodptr+m);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.