Char数组指针(cin.get& cout)

时间:2013-10-29 19:44:50

标签: c++ user-input

为了刷新我的概念,我正在研究并行数组。一个用于存储整数数据,另一个用于char数据,即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;
    }
}

1 个答案:

答案 0 :(得分:2)

您正在尝试使用C ++语言的 part ,但并未完全接受它。您无需管理内存(根本没有)来解决此问题。此外,使用标准语言功能解决它会好得多:

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循环更改为std::copy操作,可以很容易地将其转换为超过5(例如几乎无限)的帐户。

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

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;