[英]unexpected output in c++ program
我正在一個研討會上工作,我已經完成了它,但我在調試時遇到了麻煩。
該程序編譯並運行,但我遇到了一個問題,在要求用戶輸入數據並發送到顯示功能后,它顯示垃圾。
我已經通過調試模式運行了程序,我得出的結論是輸入沒有傳遞給我的 setter 函數,但是在我教授寫的代碼中(他寫了主要內容並要求我們填寫一些內容,例如內存分配)它不要求我在 main 中初始化 setter 函數,我錯過了什么嗎?
'Weather.h' 文件是集合和顯示函數在 Weather 類中的位置。
#include <iostream>
#include "Weather.h"
using namespace std;
using namespace sict;
int main(){
int n; //the count of days worth of weather
// initialize the weather pointer here
Weather* weather;
cout << "Weather Data\n";
cout << "=====================" << endl;
cout << "Days of Weather: ";
cin >> n;
cin.ignore();
// allocate dynamic memory here
weather = new Weather[n];
for (int i = 0; i < n; i++){
char date_description[7];
double high = 0.0, low = 0.0;
// ... add code to accept user input for
//weather
cout << "Enter date: ";
cin >> date_description;
cout << "Enter high: ";
cin >> high;
cout << "Enter low: ";
cin >> low;
}
cout << endl;
cout << "Weather report:\n";
cout << "======================" << endl;
for (int i = 0; i < n; i++){
weather[i].display();
}
// deallocate dynamic memory here
delete[] weather;
weather = (Weather*)0;
return 0;
}
/*
Output Example :
Weather Data
== == == == == == == == == == =
Days of Weather : 3
Enter date : Oct / 1
Enter high : 15
Enter low : 10
Enter date : Nov / 13
Enter high : 10
Enter low : 1.1
Enter date : Dec / 15
Enter high : 5.5
Enter low : -6.5
Weather report :
== == == == == == == == == == ==
Oct / 1_______15.0__10.0
Nov / 13______10.0___1.1
Dec / 15_______5.5__ - 6.5
*/
set函數的定義(在天氣中):
void Weather::set(const char* Date, double high, double low){
strcpy(date, Date);
tempHigh = high;
tempLow = low;
}
您讀取數據並在weather = new Weather[n];
之后將它們放入for 循環中weather = new Weather[n];
.
您將不得不將它們儲存起來以備weather
。 應該可以這樣做:
for (int i = 0; i < n; i++){
const int store_length = 7;
char date_description[16];
char date_description_to_store[store_length];
int store_pos = 0;
double high = 0.0, low = 0.0;
// ... add code to accept user input for
//weather
cout << "Enter date: ";
cin.getline(date_description, sizeof(date_description) / sizeof(date_description[0]));
for (int i = 0; date_description[i] != '\0' && store_pos < store_length - 1; i++){
if (date_description[i] != ' ') date_description_to_store[store_pos++] = date_description[i];
}
date_description_to_store[store_pos] = '\0';
cout << "Enter high: ";
cin >> high;
cout << "Enter low: ";
cin >> low;
weather[i].set(date_description_to_store, high, low); // add this line
cin.ignore(); // add this line to ignore the new line
}
更新:您應該使用cin.getline
讀取包含空格的字符串,例如Oct / 1
。
更新 2: 7 個字符的緩沖區不足以讀取Oct / 1
。 您將不得不分配更多內存或使用std::string
。
更新 3 :您必須將Oct / 3
等輸入格式轉換為Jan/21
等存儲格式。 請注意,此代碼中沒有錯誤檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.