gpt4 book ai didi

c++ - 如何读取用户输入的逗号分隔整数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:14:26 51 4
gpt4 key购买 nike

我正在编写一个提示用户输入的程序:

  1. 数组的大小
  2. 要放入数组的值

第一部分没问题,我创建了一个动态分配的数组(必需)并使其成为用户想要的大小。

我卡在了下一部分。用户应输入一系列以逗号分隔的整数,例如:1,2,3,4,5

我如何接收这些整数并将它们放入动态分配的数组中?我读到默认情况下 cin 接受由空格分隔的整数,我可以将其更改为逗号吗?

请用最简单的方式解释,我是编程初学者(抱歉!)

编辑:所有答案都是 TY。问题是我们还没有涉及 vector ...是否有一种方法只使用我拥有的动态分配的数组?

到目前为止,我的函数看起来像这样。我在 main 中创建了一个默认数组。我打算将它传递给这个函数,创建新数组,填充它,并更新指针以指向新数组。

int *fill (int *&array, int *limit) {

cout << "What is the desired array size?: ";
while ( !(cin >> *limit) || *limit < 0 ) {
cout << " Invalid entry. Please enter a positive integer: ";
cin.clear();
cin.ignore (1000, 10);
}

int *newarr;
newarr = new int[*limit]
//I'm stuck here
}

最佳答案

现有的所有答案都非常好,但都是针对您的特定任务的。因此,我编写了一些通用代码,允许以标准方式输入逗号分隔值:

template<class T, char sep=','>
struct comma_sep { //type used for temporary input
T t; //where data is temporarily read to
operator const T&() const {return t;} //acts like an int in most cases
};
template<class T, char sep>
std::istream& operator>>(std::istream& in, comma_sep<T,sep>& t)
{
if (!(in >> t.t)) //if we failed to read the int
return in; //return failure state
if (in.peek()==sep) //if next character is a comma
in.ignore(); //extract it from the stream and we're done
else //if the next character is anything else
in.clear(); //clear the EOF state, read was successful
return in; //return
}

示例用法 http://coliru.stacked-crooked.com/a/a345232cd5381bd2 :

typedef std::istream_iterator<comma_sep<int>> istrit; //iterators from the stream
std::vector<int> vec{istrit(in), istrit()}; //construct the vector from two iterators

由于您是初学者,这段代码现在对您来说可能太多了,但我想为了完整起见我会发布它。

关于c++ - 如何读取用户输入的逗号分隔整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21837521/

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