我正在编写一个程序,提示用户:
第一部分很好,我创建了一个动态分配的数组(必需)并使其成为用户想要的大小。
我被困在下一部分。用户应输入一系列由逗号分隔的整数,例如:1,2,3,4,5
我如何接收这些整数并将它们放入我动态分配的数组中?我读到默认情况下 cin 接受以空格分隔的整数,我可以将其更改为逗号吗?
请以最简单的方式解释,我是编程初学者(对不起!)
编辑: TY 这么多答案。问题是我们还没有涵盖向量......有没有一种方法只使用我拥有的动态分配的数组?
到目前为止,我的函数看起来像这样。我在 main.js 中创建了一个默认数组。我计划将它传递给这个函数,创建新数组,填充它,并更新指针以指向新数组。
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
}
Run Code Online (Sandbox Code Playgroud)
所有现有的答案都非常好,但都针对您的特定任务。因此,我编写了一些通用代码,允许以标准方式输入逗号分隔值:
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
}
Run Code Online (Sandbox Code Playgroud)
示例用法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
Run Code Online (Sandbox Code Playgroud)
由于您是初学者,这段代码现在对您来说可能太多了,但我想我会为了完整性而发布此代码。
您可以使用getline()如下方法:
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::string input_str;
std::vector<int> vect;
std::getline( std::cin, input_str );
std::stringstream ss(str);
int i;
while (ss >> i)
{
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
}
Run Code Online (Sandbox Code Playgroud)
该代码是从此答案中获取和处理的。
| 归档时间: |
|
| 查看次数: |
41743 次 |
| 最近记录: |