#include <iostream>
using namespace std;
struct Flight {
char flightNumber[6];
int depHour;
int depMin;
};
int main() {
char flightNumber[6];
int depHour;
int depMin;
cin.getline(flightNumber, 6);
cin >> depHour;
cin >> depMin;
Flight f = {.flightNumber = flightNumber[6], .depHour=depHour , .depMin= depMin};
cout << f.flightNumber << " " << f.depHour << " " << f.depMin << endl;
return 0;
}
无论我在飞行中放置什么数字都不会出现。编译时没有错误但无法输出flightNumber。它是空的。知道问题是什么吗?
答案 0 :(得分:3)
.flightNumber = flightNumber[6]
复制索引6处的字符。这是数组的超出范围。因此是未定义的行为。同样的错误也会导致您打印一个非空终止的字符串,这也会导致未定义的行为。
您需要使用某种形式的strncpy()
有人这么说......我很惊讶,没有任何警告就会编译(而且对于我来说,它就是铿锵声)。
#include <iostream>
using namespace std;
struct Flight {
char flightNumber[6];
int depHour;
int depMin;
};
int main() {
char flightNumber[6];
int depHour;
int depMin;
cin.getline(flightNumber, 6);
cin >> depHour;
cin >> depMin;
Flight f = {.depHour=depHour , .depMin= depMin};
strcpy(f.flightNumber, flightNumber);
cout << f.flightNumber << " " << f.depHour << " " << f.depMin << endl;
return 0;
}
#include <iostream>
using namespace std;
struct Flight {
Flight(char *flightNumber_, int depHour_, int depMin_): depHour(depHour_), depMin(depMin_) {
strcpy(flightNumber, flightNumber_);
}
char flightNumber[6];
int depHour;
int depMin;
};
int main() {
char flightNumber[6];
int depHour;
int depMin;
cin.getline(flightNumber, 6);
cin >> depHour;
cin >> depMin;
Flight f(flightNumber, depHour, depMin);
cout << f.flightNumber << " " << f.depHour << " " << f.depMin << endl;
return 0;
}
strcpy()
。使用strncpy()
和验证码确保您不会复制超出已分配数组的长度。std::string
是一个可爱的c ++类型。