-1

只是为了刷新我的概念,我正在研究并行数组。一种用于存储整数数据,另一种用于存储字符数据,即 GPA。

问题像魅力一样编译,但结果不正确,它正确显示学生 ID,但不显示 GPA。

  • 简单的cin工作正常
  • 我真的不知道如何使用cin.getcin.getline使用指针。
  • 在函数enter中,我想获取两个字符长的字符串(加上一个终止空字符)。

代码清单:

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

void enter(int *ar, char *arr, int size);
void exit(int *a, char *yo, int size);

int main()
{
   const int id = 5;
   const char grade = 5;
    int *student = new int[id];
    char *course = new char[grade];
    cout << "\n";

    enter(student, course, 5);
    exit(student, course, 5);

}

void enter(int *ar, char *arr, int size)
{
    for(int i = 0; i < size; i ++)
    {
        cout << "Student ID: " << i+1 << "\n";
        cin >> *(ar+i);
        cin.ignore();
        cout << "Student Grade: " << i+1 << "\n";
        cin.get(arr, 3);
    }
}

void exit(int *a, char *yo, int size)
{
    for(int i = 0; i < size; i ++)
    {
        cout << "ID And Grade Of Student #" << i+1 << ":";
            cout << *(a+i) << "\t" << *(yo+j) << endl;
    }
}
4

1 回答 1

2

您正在尝试使用C++ 语言的一部分,但没有完全接受它。您根本不需要管理内存来解决这个问题。此外,使用标准语言功能解决它会更好:

struct Info
{
    int StudentId;
    std::string Grade; // this could easily be stored as an int or a char as well
};

int main()
{
    const std::vector<Info>::size_type SIZE_LIMIT = 5;
    std::vector<Info> vec(SIZE_LIMIT);
    for (std::vector<Info>::size_type i = 0; i < SIZE_LIMIT; ++i)
    {
        std::cout << "Enter a Student ID:  ";
        std::cin >> vec[i].StudentId;
        std::cout << "Enter a Grade:  ";
        std::cin >> vec[i].Grade;
    }

    std::for_each(vec.begin(), vec.end(), [&](const Info& i)
    {
        std::cout << "Student ID:  " << i.StudentId << ", Grade:  " << i.Grade << std::endl;
    });

    return 0;
}

std::istream& operator>>(std::istream&, Info&)通过添加重载 for并将 for 循环更改为操作,可以很容易地将其转换为超过 5 个(例如几乎无限)std::copy

如果你绝对想把双手绑在背后,你至少应该做出以下改变:

const unsigned int CLASS_SIZE = 5;
const unsigned int GRADE_SIZE = 5;
int student[CLASS_SIZE];
char course[CLASS_SIZE][GRADE_SIZE] = {};

// initialize course grades to empty strings, if you don't use the = {} above
for (unsigned int i = 0; i < CLASS_SIZE; ++i)
{
    memset(course[i], 0, GRADE_SIZE);
}

// ... 

// use your constants for your sizes
enter(student, course, CLASS_SIZE);
exit(student, course, CLASS_SIZE);

// ...

// NOTE:  you should check to make sure the stream is in a good condition after each input - I leave the error checking code for you to implement
cout << "Student ID: ";
cin >> ar[i];
cout << "Student Grade: ";
cin >> arr[i]; // also note:  since you are not using std::string, this can overflow!  careful!

// ...

cout << "ID And Grade Of Student #" << i+1 << ":" << a[i] << "\t" << yo[i] << endl;
于 2013-10-29T20:06:50.060 回答