问题描述
Navigator.of(context).pop();
我正在尝试运行此代码,但是当我尝试使用“ -1073741819”退出代码键入任何食物名称时,它退出了,这是怎么做的呢?
解决方法
T temp{};
正在将temp
初始化为nullptr
,所以您不能让它在那里读取内容。
您应该改用std::string
:
#include <iostream>
#include <string> // add this to use std::string
#include <list>
#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl
template<typename T>
T input(const char* string) {
print(string);
T temp{};
std::cin >> temp;
return temp;
}
int main() {
std::list<std::string> list_of_foods;
std::string food;
while (1) {
food = input<std::string>("Enter a food name or (exit) to exit: ");
if (food == "exit") { break; }
else { list_of_foods.push_back(food); }
}
std::list<std::string>::iterator food_iterator = list_of_foods.begin();
println("Your order is:");
while (food_iterator != list_of_foods.end()) {
println(*food_iterator);
food_iterator++;
}
}
无论如何,如果您想使用char*
,模板特化对于分配缓冲区很有用。
另外请注意,无法通过==
完成C样式字符串的比较,而应使用strcmp()
。
#include <iostream>
#include <cstring> // for using strcmp()
#include <list>
#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl
template<typename T>
T input(const char* string) {
print(string);
T temp{};
std::cin >> temp;
return temp;
}
template<>
char* input(const char* string) {
print(string);
char* temp = new char[1024000]; // allocate enough size and pray not to be attacked
std::cin >> temp;
return temp;
}
int main() {
std::list<char*> list_of_foods;
char* food;
while (1) {
food = input<char*>("Enter a food name or (exit) to exit: ");
if (strcmp(food,"exit") == 0) { break; }
else { list_of_foods.push_back(food); }
}
std::list<char*>::iterator food_iterator = list_of_foods.begin();
println("Your order is:");
while (food_iterator != list_of_foods.end()) {
println(*food_iterator);
food_iterator++;
}
}
,
当您使用folder.expunge()
模板参数调用input
时,该函数的主体变为:
char*
在这种情况下,// ...
char * temp{};
std::cin >> temp;
// ...
没有指向有效的内存,并且尝试向其中读取一个值将调用未定义的行为。
您应该只使用char*
,因为std::string
可以读入输入而无需手动分配内存。