【问题标题】:Letting users write to a list [closed]让用户写入列表[关闭]
【发布时间】:2013-01-20 20:15:36
【问题描述】:

我是 C++ 新手,我正在尝试制作一个程序,以允许运行该程序的任何人写入列表,当他们完成键入“exit”时,它将显示列表。我不知道如何实现这一目标,有人可以帮忙吗?

这是我所拥有的:

#include <iostream>
#include <string>
#include <unistd.h>
#include <math.h>
#include <vector>

using namespace std;
int main()
{
    string uid;
    write(1,"\E[H\E[2J",7);
    cout << "Enter UID: ";
    cin >> uid;
    cout << "DB: \n\n" << uid << " \n\n""end\n\n";
    return 0;
}

我怎样才能把它放在一个循环中,以便他们每个人都可以继续写入列表,直到他们输入“退出”?

【问题讨论】:

  • 你知道怎么写循环吗?
  • 什么是'\E'?也许这应该是'\x1B'?
  • 那些是我用来清除终端窗口的 ascii 转义字符

标签: c++ arrays list vector


【解决方案1】:

std 中有一个列表 - std::list。查一下。有向其中插入元素的函数,您可以在最后遍历它以打印值。

循环很简单

do{
    //whatever you want to do in the loop
    //read input
    //insert into list
}while(/*condition*/); //condition should be something like
                       //the string is not "exit"

std::string 具有与其他字符串进行比较的方法以及重载的运算符。找到要使用的对您来说是一个很好的练习。

没有给出实际代码是因为……好吧,那对你没有太大帮助,不是吗?

【讨论】:

  • 虽然这里没有真正的理由更喜欢std::list 而不是std::vector
  • @juanchopanza 好吧,这是要求的一部分,但仅此而已。 :)
  • 谢谢,正在查找。但是“实际代码”会非常有帮助。感谢您的快速回复
  • @user1995298 不,您认为会有所帮助,但不会。
  • 我不确定 OP 是否真的意味着 std::list。可能需要提一下,在大多数情况下,这不是一个好的选择。
【解决方案2】:

由于这个问题不费吹灰之力,我会给出一个你根本无法理解的复杂答案......

std::vector<std::string> list;
for(std::string i; std::cin >> i && i != "exit"; list.push_back(i));
std::copy(list.begin(), list.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

.. 但可能是最小的方法(我相信有人会做一个更小的现在我说过)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 2020-01-16
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多