#include <iostream>
#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<char*> list_of_foods;
    char* food;
    while (1) {
        food = input<char*>("Enter a food name or (exit) to exit: ");
        if (food == "exit") { 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++;
    }
}
我正在尝试运行此代码,但是当我尝试使用“-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++;
    }
}

10-05 18:16