私はプログラミングが初めてです。私の教科書では、ユーザーに 3 か月間の降雨量を尋ねて平均を計算するプログラムを作成する問題が提示されていました。
cin.getline() 関数を使用して、ユーザー入力を配列に読み込みました。テキストには、cin.getline() 関数を使用して配列がオーバーフローする心配はないと記載されています。ただし、配列よりも大きな文字列を入力すると、プログラムがうまくいかなくなります。なぜこれが起こるのですか?
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int SIZE = 10;
char month1[SIZE], month2[SIZE], month3[SIZE];
double rain1, rain2, rain3, average;
cout << "Enter the name of the first month: ";
cin.getline(month1,SIZE);
cout << "Enter the rainfall for " << month1 << ": ";
cin >> rain1;
cin.ignore();
cout << "Enter the name of the second month: ";
cin.getline(month2,SIZE);
cout << "Enter the rainfall for " << month2 << ": " ;
cin >> rain2;
cin.ignore();
cout << "Enter the name of the third month: ";
cin.getline(month3,SIZE);
cout << "Enter the rainfall for " << month3 << ": ";
cin >> rain3;
cin.ignore();
average = (rain1 + rain2 + rain3)/3;
cout << fixed << showpoint << setprecision(2)
<< "The average rainfall for " << month1 << ", " << month2
<< ", and " << month3 << " is " << average << " inches\n\n";
return 0;
}