gpt4 book ai didi

c++ - 如何在一行中用户输入c++中的数组元素

转载 作者:行者123 更新时间:2023-11-30 01:13:20 26 4
gpt4 key购买 nike

本人初学c++,基本属于PHP。所以我正在尝试编写一个程序来练习,对数组进行排序。我已经成功创建了静态数组值为

的程序
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector


bool myfunction (int i,int j) { return (i<j); }

struct myclass { bool operator() (int i,int j) { return (i<j);} } myobject;

int main () {
int myints[] = {55,82,12,450,69,80,93,33};
std::vector<int> myvector (myints, myints+8);

// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4);

// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction);

// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);

// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}

它的输出没问题。但我希望元素应该从用户输入, space separated 或 , separated 。所以我试过了

int main () {
char values;
std::cout << "Enter , seperated values :";
std::cin >> values;
int myints[] = {values};


/* other function same */
}

它在编译时没有抛出错误。但是 op 并不像要求的那样。这是

Enter , seperated values :20,56,67,45

myvector contains: 0 0 0 0 50 3276800 4196784 4196784

------------------ (program exited with code: 0) Press return to continue

最佳答案

你可以使用这个简单的例子:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

int main()
{
stringstream ss;
string str;
getline(cin, str);
replace( str.begin(), str.end(), ',', ' ');
ss << str;

int x = 0;
while (ss >> x)
{
cout << x << endl;
}
}

Live demo


或者,如果你想让它更通用并且很好地包含在返回 std::vector 的函数中:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>

using namespace std;

template <typename T>
vector<T> getSeparatedValuesFromUser(char separator = ',')
{
stringstream ss;
string str;
getline(cin, str);
replace(str.begin(), str.end(), separator, ' ');
ss << str;

T value{0};
vector<T> values;
while (ss >> value)
{
values.push_back(value);
}

return values;
}

int main()
{
cout << "Enter , seperated values: ";
auto values = getSeparatedValuesFromUser<int>();

//display values
cout << "Read values: " << endl;
for (auto v : values)
{
cout << v << endl;
}
}

Live demo

关于c++ - 如何在一行中用户输入c++中的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32440156/

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