gpt4 book ai didi

c++ - 如何允许用户输入数组索引以及数组的值?

转载 作者:行者123 更新时间:2023-11-30 02:35:55 26 4
gpt4 key购买 nike

#include <iostream>
#include <algorithm>
using namespace std;

int main(){

string m;
int n;

cout << "How many elements would you like to sort?" << endl;

cin >> n; //index for the array



cout << "Enter " << n << " numbers seperated by a comma to be sorted" << endl;

cin >> m;

string unsortedNumbers[n]={m}; // values inputed stored as array values
cout << m << endl;

std::sort(m.begin() , m.end()); //sorting string m
std::cout<< m << endl;

}

我知道代码是错误的,如果您运行代码,“字符串”在排序之前可以正常工作。当对大于 10 的数字进行排序时,它会将它们分解为 1 和 0。此外,所有逗号都会排序并表示您的输入是 2,3,4,5,您的输出将类似于 ,,,,2345。所以我的问题是如何让用户选择索引大小,同时允许他们输入的任何数字来确定要排序的变量数量?

最佳答案

我只能以一种安静而繁琐的方式执行此操作,因为我将 string 转换为 char*,最后再次将 char* 转换为 string。在我看来,C++ 标准库的字符串类使您能够将字符串用作普通类型,不会给用户带来任何问题。因此,您可以将字符串作为基本类型进行复制、分配和比较,而不必担心或烦恼是否有足够的内存或内部内存的有效期。然而,这也意味着我们只能使用接口(interface),不能为所欲为。要知道,string基于基本模板类basic_string<>,看起来比char*更像容器。

#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
string m;
int n;
cout << "How many elements would you like to sort?" << endl;
cin >> n; //index for the array
cout << "Enter " << n << " numbers seperated by a comma to be sorted" << endl;
cin >> m;


//string c[n]={m};
vector<int> unsortedNumbers;
const char* p=m.c_str();
int i=0;
while(i<n){//or *p!='\0'
i++;
unsortedNumbers.push_back(atoi(p));
while(*p>='0'&&*p<='9') p++;
if(i<n)p++;
}
//std::sort(m.begin() , m.end()); //sorting string m
sort(unsortedNumbers.begin(), unsortedNumbers.end());
for_each(unsortedNumbers.begin(), unsortedNumbers.end(), [](int x){cout<<x<<" ";});
//now we have a sorted array and its type is double[]
char arr[n][m.length()];
for(int i=0;i!=n;i++) {
if(i!=n-1) sprintf(arr[i],"%d,",unsortedNumbers[i]);
else sprintf(arr[i],"%d",unsortedNumbers[i]);
}
m.clear();
for(auto i:arr) m+=i;
cout<<m;
}

关于c++ - 如何允许用户输入数组索引以及数组的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33313029/

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