1

我一直在尝试将此数组传递给函数,但我不断收到 错误 C2664: 'correctans' : cannot convert parameter 2 from 'std::string [3][3]' to 'std::string ** ',不要介意代码中的愚蠢问题,它只是随机测试。

代码:

    #include <iostream>
    #include <string>
    using namespace std;

int correctans(string *arr1, string **arr2, int *arr3, int questions, int choices)
{
int count=0;
int ans;

    for(int i=0; i<questions; i++)
    {
        cout << "Question #" << i+1;
      cout << arr1[i] << endl;
      for(int j=0; j<choices; j++)
          cout << j+1 << arr2[i][j] << " ";
      cout << "your answer:";
      cin >> ans;
      if(ans==arr3[i])
          count++;
    }

    return count;
}

int main()
{
    int correct;
    string Questions[3]={"HowAreYou", "HowManyHandsDoYouHave", "AreYouCrazyOrCrazy"};
    string Choices[3][3]={{"Banana", "Peanut", "Fine"},{"Five", "Two", "One"},{"I'mCrazy", "I'mCrazyBanana", "I'mDoubleCrazy"}};
    int Answers[3]={3, 2, 3};

    correct=correctans(Questions, Choices, Answers, 3, 3);
    cout << "You have " << correct << " correct answers" <<endl;

    return 0;
}
4

4 回答 4

1

干得好

整数更正(字符串 *arr1,字符串(&arr2)[3][3],整数 *arr3,整数问题,整数选择)`

于 2013-06-10T15:19:29.330 回答
1

传递多维数组会变得非常混乱。我建议创建一个指向数组开头的单指针,并​​传递该指针:

    #include <iostream>
    #include <string>
    using namespace std;

int correctans(string *arr1, string *arr2, int *arr3, int questions, int choices)
{
int count=0;
int ans;

    for(int i=0; i<questions; i++)
    {
        cout << "Question #" << i+1;
      cout << arr1[i] << endl;
      for(int j=0; j<choices; j++)
          cout << j+1 << arr2[i][j] << " ";
      cout << "your answer:";
      cin >> ans;
      if(ans==arr3[i])
          count++;
    }

    return count;
}

int main()
{
    int correct;
    string Questions[3]={"HowAreYou", "HowManyHandsDoYouHave", "AreYouCrazyOrCrazy"};
    string Choices[3][3]={{"Banana", "Peanut", "Fine"},{"Five", "Two", "One"},{"I'mCrazy", "I'mCrazyBanana", "I'mDoubleCrazy"}};
    int Answers[3]={3, 2, 3};

    string* choicesPtr=&Choices[0][0];
    correct=correctans(Questions, choicesPtr, Answers, 3, 3);
    cout << "You have " << correct << " correct answers" <<endl;

    return 0;
}

此代码编译并执行。

于 2013-06-10T15:23:00.067 回答
0

如果我没记错的话,你可以使用类似'string [][] & rArray'
(或者确切地说:string [3][3] & rArray),当然你也应该将实际尺寸作为参数传递。

编译器接受了这个:
字符串 arr2[3][3]
作为参数。但我会尝试改进传递指针而不是按值复制数组。由于您使用的是 stl::string,因此您也可以尝试使用 vector<vector<string>>。

于 2013-06-10T15:14:01.533 回答
0

好吧,正如编译器所说std::string [3][3],不能转换为std::string **.

你可以试试这个

int correctans(string *arr1, string (* arr2)[ 3 ], int *arr3, int questions, int choices)

或这个

int correctans(string *arr1, string arr2[][ 3 ], int *arr3, int questions, int choices)

但更好的解决方案是使用std::vector.

于 2013-06-10T15:14:54.727 回答