【问题标题】:How can I separate user inputted string and store it into an array如何分离用户输入的字符串并将其存储到数组中
【发布时间】:2013-09-23 17:54:55
【问题描述】:

我想知道您是否可以在不使用 strtok 之类的东西的情况下帮助我解决这个问题。这个任务是为了让我构建一些可以接受输入并将用户引导到正确区域的东西。我想得到类似......

帮助复制

并将其存储为

数组[1] = 帮助
数组[2] = 复制。

我试图做类似 cin>>arr[1];和 cin>>arr[2] 但同时如果用户输入 copy 那么我不知道该怎么做

基本上,我不确定如何接受任何大小的输入并将它们作为元素放入数组中的任何内容存储。

我会尝试 cin.get 或 getline 之类的方法,但它们似乎并没有真正帮助我,而且我的 cin 想法根本没有帮助。

这是我目前所拥有的。

int main()
{
    string user;

    cout<<"Hello there, what is your desired username?"<<endl;

    cin >> user;

    system("cls");

    cout<<"Hello, " << user << "! How are you doing?"<<endl<<endl;

    cout<< user << ": ";



    return 0;
}

【问题讨论】:

  • 你用的是什么数组?如果你不使用 std::vector 会简化事情。
  • " .. 但同时如果用户输入 copy " 我不明白那部分。
  • 抱歉,我上传了旧版本。我还没有在这里添加数组,但我听说过向量的东西,但它到底是做什么的。我知道去谷歌的短途旅行会有所帮助,但我希望得到您的意见。
  • 可以将输入的字符串在空格处分割并存储到对应的数组中。

标签: c++ arrays string


【解决方案1】:

你可以这样做:

  • 使用getline读取整行
  • 从该行创建一个输入字符串流
  • 将该字符串流的内容读入vector&lt;string&gt;。它会自动增长以适应用户输入的尽可能多的输入
  • 检查结果向量的大小以查看最终用户输入了多少条目

以下是您可以在代码中执行此操作的方法:

// Prepare the buffer for the line the user enters
string buf;
// This buffer will grow automatically to accommodate the entire line
getline(cin, buf);
// Make a string-based stream from the line entered by the user
istringstream iss(buf);
// Prepare a vector of strings to split the input
vector<string> vs;
// We could use a loop, but using an iterator is more idiomatic to C++
istream_iterator<string> iit(iss);
// back_inserter will add the items one by one to the vector vs
copy(iit, istream_iterator<string>(), back_inserter(vs));

这是demo on ideone

【讨论】:

    【解决方案2】:
    std::vector<std::string> myInputs;
    
    std::cout << "Enter parameters:  ";
    std::copy(std::istream_iterator<std::string>(std::cin), std::isteram_iterator<std::string>(), std::back_inserter(myInputs));
    
    // do something with the values in myInputs
    

    如果用户在每个输入之间按 Enter,这将一直持续到他们停止输入(Windows 上的 Crtl-D)。如果您希望他们将所有参数放在一行中,您可以将输入读入单个字符串,然后用空格(或您希望使用的任何分隔符)拆分字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多