如何使用用户输入使字符串排队?

问题描述 投票:0回答:1

我想知道如何使需要用户输入的字符串队列。例如,用户将输入一个单词,然后该单词进入队列。这是如何运作的?我现在只能将整数排队。抱歉,我是一个初学者,我们的教授没有教我们任何东西:(

c++ queue
1个回答
3
投票

您可以使用默认的STD队列。查阅此文档,Queue

std::queue类是一种容器适配器,为程序员提供了队列的功能,特别是FIFO(先进先出)数据结构。

注意,这与在为典型的大学课程设计的class设计的[[您自己的中实现队列非常不同。

[您只需要声明类型为std::queuestd::string,例如std::queue<std::string> q

#include <iostream> #include <string> #include <queue> #include <stack> #include <ostream> #include <istream> int main () { // Declare your queue of type std::string std::queue<std::string> q; // Push 1 to 3 q.push ("1"); q.push ("2"); q.push ("3"); // Declare a string variable std::string input; // Prompt std::cout << "- Please input a string: " << std::endl; // Catch user input and store std::cin >> input; // Push value inputted by the user q.push(input); // Loop while the queue is not empty, while popping each value while (not q.empty ()) { // Output front of the queue std::cout << q.front () << std::endl; // Pop the queue, delete item q.pop (); } // New line, formatting purposes std::cout << std::endl; return 0; }

© www.soinside.com 2019 - 2024. All rights reserved.