如何从用户那里获取输入并将其推送到列表

How to get input from the user and push it to a list

#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”退出代码的任何食物名称时它退出了,我到底做错了什么?

当您使用 char* 模板参数调用 input 时,函数主体变为:

// ...
char * temp{};
std::cin >> temp;
// ...

在这种情况下,char* 未指向有效内存,并且尝试将值读入其中将调用未定义的行为。

您应该只使用 std::string,因为 string 无需手动分配内存即可读取输入。

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-style 字符串的比较不能通过 == 完成,您应该使用 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++;
    }
}