gpt4 book ai didi

c++ - 如何分离用户输入的字符串并将其存储到数组中

转载 作者:行者123 更新时间:2023-11-30 01:57:17 25 4
gpt4 key购买 nike

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

Help Copy

并将其存储为

array[1] = Help
array[2] = Copy.

我试着做一些像 cin>>arr[1];和 cin>>arr[2] 但同时如果用户输入 copy 那么我不知道该怎么做因为如果我只放一个 cin 那么如果用户输入 help 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;
}

最佳答案

你可以这样做:

  • 使用 getline 读取整行
  • 从该行创建一个输入字符串流
  • 将该字符串流的内容读入 vector<string> .它会自动增长以适应用户输入的输入量
  • 检查结果 vector 的大小以查看最终用户输入了多少

这里是你如何在代码中做到这一点:

// 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 .

关于c++ - 如何分离用户输入的字符串并将其存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18881272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com