-3

C++ detailed modifications i need help doing to this codeпередачи массивов в функции

я нужна помощь в создании 7 функций сломать этот код в. Используя проход по ссылке. Я не могу понять, как передать многомерные массивы между функциями.

#include <fstream> 
#include <string> 
#include <iomanip> 
#include <iostream> 
#include <cmath> 
using namespace std; 


int main() 
{ 


const int courseSize = 3; 
const int examSize = 6; 
int n=0; 
int strLength =0; 
double scoreTotal =0; 
char lettergrade; 

string header, name, address, phone, social, course, studentID; 
const int letterGrade_A = 90; 
const int letterGrade_B = 80; 
const int letterGrade_C = 70; 
const int letterGrade_D = 60; 

int age, yearsAtTXST, numstudents; 
double testscore; 
double numGrade = 0; 
const int minStrLength = 1; 
const int maxStrLength = 100; 
const int minint = 1; 
const int maxint = 100; 
const int minCourse = 1; 
const int maxCourse = 3; 
const int minTest = 1; 
const int maxTest = 5; 
const double test1 = 0.10; 
const double test2 = 0.15; 
const double test3 =0.15; 
const double test4 = 0.20; 
const double final_test = 0.40; 
const double maxGrade = 100.0, minGrade = 1.0; 

//initialize arrays 
string nonNumerical[studsize][strSize]; 
int numeric1[studsize][numSize]; 
double numeric2[studsize][courseSize][examSize]; 
char lettergrades[studsize][courseSize]; 

cout << fixed << showpoint << setprecision(2); 

//opening files 
ifstream inputFile; 
inputFile.open("Project4_A04314548_Input.txt"); 
ofstream fout; 
fout.open ("Project4_A04314548_Output.txt"); 

if(!(inputFile && fout)) 
{ 
    cout << "Error opening file.\n"; 
} 


cout << " Enter a number of students: "; 
cin >> numstudents; 

while(!(numstudents ==3)) 
{ 
    cout << " error number of students must be 3. Enter again: "; 
    cin >> numstudents; 
} 

//take in string data from input file 
for(int x =0; x< studsize; x++) 
{ 
    for(int y=0; y < strSize; y++) 
    { 
     if(y >= strSize) 
     break; 

     getline(inputFile, nonNumerical[x][y]); 
     strLength = nonNumerical[x][y].length(); 
     if(strLength < minStrLength || strLength > maxStrLength) 
     { 
     fout << " The given string for nonNumerical [" << x << "][" << y <<         

    "] is not within the proper range of 1-100 characters." << endl; 
     fout << " Please fix the issue and rerun the program for a correct  

    output." << endl << endl; 
     continue; 
     } 
    } 
    } 

//above put into input data function 

    //take in data from input file 
for(int x=0; x<studsize;x++) 
{ 
    for(int y=0; y < numSize; y++) 
    { 
     if(y>=numSize) 
      break; 

     inputFile >> numeric1[x][y]; 
     if(numeric1[x][y] < minint || numeric1[x][y] > maxint) 
     { 
     fout << "The given integer for numerical1[" << x << "][" << y << 
    "]is not within the proper range of 1-100." << endl; 
     fout << " please fix the problem and rerun the program for a correct  
    output." << endl << endl; 
     break; 
     } 

    } 
    } 

    //above put into data function 

    // take in double data from input file 
    for(int x1=0; x1<studsize; x1++) 
    { 
    for(int x2=0; x2 < courseSize; x2++) 
    { 
     for(int x3=0; x3<(examSize-1);x3++) 
     { 
      if(x3 >=(examSize-1)) 
       break; 
      inputFile >> numeric2[x1][x2][x3]; 
      if(numeric2[x1][x2][x3] < minGrade || numeric2[x1][x2][x3] > 
     maxGrade) 
      { 
       cout << "The given value fro numeric2[" << x1 << "][" << x2 
    << "][" << x3 << "] is not within the proper range of 1-100" << endl 
       << "Please fix the issue and rerun the program for a correct 
    output." << endl; 
       break; 
      } 

      else if(x3 == 0) 
       scoreTotal += (numeric2[x1][x2][x3]* test1); 
      else if(x3== 1) 
       scoreTotal += (numeric2[x1][x2][x3]* test2); 
      else if(x3 == 2) 
       scoreTotal += (numeric2[x1][x2][x3]* test3); 
      else if(x3 == 3) 
       scoreTotal += (numeric2[x1][x2][x3]* test4); 
      else 
       scoreTotal += (numeric2[x1][x2][x3]* final_test); 
      } 

      numeric2[x1][x2][5] = scoreTotal; // final numeric grade 
      scoreTotal = 0; 

      if(x2 >=courseSize) 
       break; 
      if((numeric2[x1][x2][5] > maxGrade) || (numeric2[x1][x2][5] < 
    minGrade)) 
      { 
       cout << "Error in calculating grade. Please fix the issue 
    then rerun the program. ignore broken program!"; 
       cout << endl << endl; 
       continue; 

      } 

      else if(numeric2[x1][x2][5] >= letterGrade_A) 
       lettergrades[x1][x2] = 'A'; 
      else if(numeric2[x1][x2][5] >= letterGrade_B) 
       lettergrades[x1][x2] = 'B'; 
      else if(numeric2[x1][x2][5] >= letterGrade_C) 
       lettergrades[x1][x2] = 'C'; 
      else if(numeric2[x1][x2][5] >= letterGrade_D) 
       lettergrades[x1][x2] = 'D'; 
      else 
       lettergrades[x1][x2] = 'F'; 

    } 
    } 

    for(int a1=0; a1< studsize; a1++) 
    { fout << nonNumerical[a1][0]<< endl; 
     fout << right << setw(35) << "Name of Student:\t"; 
     fout << nonNumerical[a1][1] << endl; 
     fout << right << setw(35) << "Student ID:\t"; 
     fout << nonNumerical[a1][2]<< endl; 
     fout << right << setw(35) << "Address:\t" ; 
     fout << nonNumerical[a1][3] << endl; 
     fout << right << setw(35) << "Telephone Number:\t"; 
     fout << nonNumerical[a1][4] << endl; 
     fout << right << setw(35) << "Student Soc. Security:\t"; 
     fout << nonNumerical[a1][5] << endl; 
     fout << right << setw(35) << "Age:\t"; 
     fout << numeric1[a1][0] << endl; 
     fout << right << setw(35) << "Number of years at Texas State:\t"; 
     fout << numeric1 [a1][1] << endl << endl; 




    for(int b1=0; b1 <courseSize; b1++) 
    { 
     fout << right << setw(35) << "Course number:\t"; 
      fout << nonNumerical[a1][(b1+6)] << endl; 

     for(int c1= 0; c1 <(examSize-1); c1++) 
     { 
     fout << right << setw(32) << "Exam #" << (a1 +1) << ":\t"; 
      fout << numeric2[a1][b1][c1] << endl; 
     } 

     fout << right << setw(35) << "Numerical grade:\t"; 
     fout << numeric2[a1][b1][5] << endl; 
     fout << right << setw(35) << "Letter grade:\t"; 
     fout << lettergrades[a1][b1] << endl; 

     if(numeric2[a1][b1][5] < 70) 
     { 
     fout << right << setw(14) << " Warning Note: Your grade is too low 
    and needs improvements!" << endl << endl; 
     } 
     else if (numeric2[a1][b1][5] >= 95) 
     { 
     fout << right << setw(14) << " Appreciation Note: Congratulations, 
    Your performance is Excellent!" << endl << endl; 
     } 
     else 
     fout << endl; 



    } 
    fout << endl; 

} 

inputFile.close(); 
fout.close(); 

    return 0; 
} 
+1

Для демонстрации вашей проблемы достаточно двух функций. Это просто способ много кода. Я даже не могу найти ваши функции. – user463035818

+2

Как вы узнаете, все ли сделано для вас кем-то еще? – Slava

+0

http://stackoverflow.com/questions/8767166/passing-a-2d-array-to-ac-function –

ответ

1

Вместо использования массива

std::string nonNumerical[studsize][strSize]; 

использования std::vector.

std::vector<std::vector<std::string>> nonNumerical(studsize, std::vector<std::string(strSize)); 

Затем вы можете разделить свой код на столько функций, сколько вам нужно, и передать векторы в функции.

void function1(std::vector<std::vector<std::string>>& nonNumerical) 
{ 
    ... 
} 

и использовать его из main как:

int main() 
{ 
    ... 

    std::vector<std::vector<std::string>> nonNumerical(studsize, std::vector<std::string(strSize)); 

    ... 

    function1(nonNumerical); 

    ... 
} 
0

прежде всего C++ отправить массивы по ссылке. ваш вопрос не ясно ... но если у меня есть это право, вы должны отправить двухмерные массивы, как это:

void f1(int a[][20]) ; 

только дело в том, что вы должны указать второе измерение.

+0

помните, что C++ всегда передают массивы по ссылке – shayan

+0

. Измените свой ответ для форматирования – NathanOliver

-1

Вы можете передать любой размер и размер массива с помощью указателей, как это:

myfunction1(string *nonNumerical) 
{ 
    string something=nonNumerical[0][0]; 

} 

Но не забывайте: Вы не можете задать размер массива напрямую. Вы должны каким-то образом передать размер массива.

+0

Удача, проходящая через строку array [10] [10]; 'в эту функцию. – user4581301

+0

Что вас беспокоит? Объясните, если вы начали критиковать \t и downwote. – Bady

+0

Игнорирование отсутствия типа возврата и предположения 'string *' означает 'string **', потому что альтернативы совершенно неверны, 'string array [10] [10]' не будет затухать в 'string **', поэтому вы не можете выполнить вызов функции. Лучшее, что вы можете сделать, это 'void myfunction1 (std :: string nonNumerical [] [10])'. 1D-массив будет распадаться на указатель. 2D будет распадаться на указатель на массив, а не на указатель (или указатель на указатель). – user4581301