繁体   English   中英

C++ 项目中的指针/引用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM