C++ 如何读入用户输入的逗号分隔整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21837521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read in user entered comma separated integers?
提问by Ian004
I'm writing a program that prompts the user for:
我正在编写一个程序,提示用户:
- Size of array
- Values to be put into the array
- 数组大小
- 要放入数组的值
First part is fine, I create a dynamically allocated array (required) and make it the size the user wants.
第一部分很好,我创建了一个动态分配的数组(必需)并使其成为用户想要的大小。
I'm stuck on the next part. The user is expected to enter in a series of ints separated by commas such as: 1,2,3,4,5
我被困在下一部分。用户应输入一系列由逗号分隔的整数,例如:1,2,3,4,5
How do I take in those ints and put them into my dynamically allocated array? I read that by default cin takes in integers separated by whitespace, can I change this to commas?
我如何接收这些整数并将它们放入我动态分配的数组中?我读到默认情况下 cin 接受以空格分隔的整数,我可以将其更改为逗号吗?
Please explain in the simplest manner possible, I am a beginner to programming (sorry!)
请以最简单的方式解释,我是编程初学者(对不起!)
EDIT: TY so much for all the answers. Problem is we haven't covered vectors...is there a method only using the dynamically allocated array I have?
编辑: TY 这么多答案。问题是我们还没有涵盖向量......有没有一种方法只使用我拥有的动态分配的数组?
so far my function looks like this. I made a default array in main. I plan to pass it to this function, make the new array, fill it, and update the pointer to point to the new array.
到目前为止,我的函数看起来像这样。我在 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
}
回答by Mooing Duck
All of the existing answers are excellent, but all are specific to your particular task. Ergo, I wrote a general touch of code that allows input of comma separated values in a standard way:
所有现有的答案都非常好,但都针对您的特定任务。因此,我编写了一些通用代码,允许以标准方式输入逗号分隔值:
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
}
Sample usage http://coliru.stacked-crooked.com/a/a345232cd5381bd2:
示例用法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
Since you're a beginner, this code might be too much for you now, but I figured I'd post this for completeness.
由于您是初学者,这段代码现在对您来说可能太多了,但我想我会为了完整性而发布此代码。
回答by James Kanze
A priori, you should want to check that the comma is there, and declare an error if it's not. For this reason, I'd handle the first number separately:
先验,您应该检查逗号是否存在,如果不存在则声明错误。出于这个原因,我会单独处理第一个数字:
std::vector<int> dest;
int value;
std::cin >> value;
if ( std::cin ) {
dest.push_back( value );
char separator;
while ( std::cin >> separator >> value && separator == ',' ) {
dest.push_back( value );
}
}
if ( !std::cin.eof() ) {
std::cerr << "format error in input" << std::endl;
}
Note that you don't have to ask for the size first. The array
(std::vector
) will automatically extend itself as much as
needed, provided the memory is available.
请注意,您不必先询问尺寸。如果std::vector
内存可用,数组 ( ) 将根据需要自动扩展自身。
Finally: in a real life example, you'd probably want to read line by line, in order to output a line number in case of a format error, and to recover from such an error and continue. This is a bit more complicated, especially if you want to be able to accept the separator before or after the newline character.
最后:在现实生活中的示例中,您可能希望逐行读取,以便在出现格式错误时输出行号,并从此类错误中恢复并继续。这有点复杂,特别是如果您希望能够在换行符之前或之后接受分隔符。
回答by Victor
You can use getline()
method as below:
您可以使用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();
}
}
The code is taken and processed from thisanswer.
代码是从这个答案中获取和处理的。
回答by mattnewport
Victor's answer works but does more than is necessary. You can just directly call ignore() on cin to skip the commas in the input stream.
维克多的回答有效,但做的比必要的多。您可以直接在 cin 上调用 ignore() 以跳过输入流中的逗号。
What this code does is read in an integer for the size of the input array, reserve space in a vector of ints for that number of elements, then loop up to the number of elements specified alternately reading an integer from standard input and skipping separating commas (the call to cin.ignore()). Once it has read the requested number of elements, it prints them out and exits.
这段代码的作用是读取输入数组大小的整数,在整数向量中为该数量的元素保留空间,然后循环到指定的元素数量,交替从标准输入读取整数并跳过分隔逗号(调用cin.ignore())。一旦它读取了请求的元素数量,它就会将它们打印出来并退出。
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
using namespace std;
int main() {
vector<int> vals;
int i;
cin >> i;
vals.reserve(i);
for (size_t j = 0; j != vals.capacity(); ++j) {
cin >> i;
vals.push_back(i);
cin.ignore(numeric_limits<streamsize>::max(), ',');
}
copy(begin(vals), end(vals), ostream_iterator<int>(cout, ", "));
cout << endl;
}
回答by vaibhav
#include <iostream>
using namespace std;
int main() {
int x,i=0;
char y; //to store commas
int arr[50];
while(!cin.eof()){
cin>>x>>y;
arr[i]=x;
i++;
}
for(int j=0;j<i;j++)
cout<<arr[j]; //array contains only the integer part
return 0;
}
回答by student
#include<bits/stdc++.h>
using namespace std;
int a[1000];
int main(){
string s;
cin>>s;
int i=0;
istringstream d(s);
string b;
while(getline(d,b,',')){
a[i]= stoi(b);
i++;
}
for(int j=0;j<i;j++){
cout<<a[j]<<" ";
}
}
This code works nicely for C++ 11 onwards, its simple and i have used stringstreams and the getline and stoi functions
这段代码适用于 C++ 11 以上,它很简单,我使用了 stringstreams 以及 getline 和 stoi 函数
回答by RAM KUMAR
You can use scanf instead of cin and put comma beside data type symbol
您可以使用 scanf 而不是 cin 并将逗号放在数据类型符号旁边
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[10],sum=0;
cout<<"enter five numbers";
for(int i=0;i<3;i++){
scanf("%d,",&a[i]);
sum=sum+a[i];
}
cout<<sum;
}
回答by Prathamesh S
First, take the input as a string, then parse the string and store it in a vector, you will get your integers.
首先,将输入作为字符串,然后解析字符串并将其存储在向量中,您将获得整数。
vector<int> v;
string str;
cin >> str;
stringstream ss(str);
for(int i;ss>>i;){
v.push_back(i);
if(ss.peek() == ','){
ss.ignore();
}
}
for(auto &i:v){
cout << i << " ";
}
回答by Atul Kumar
The code can be simplified a bit with new std::stoi function in C+11. It takes care of spaces in the input when converting and throws an exception only when a particular token has started with non-numeric character. This code will thus accept input
可以使用 C+11 中的新 std::stoi 函数稍微简化代码。它在转换时处理输入中的空格,并且仅当特定标记以非数字字符开头时才抛出异常。因此,此代码将接受输入
" 12de, 32, 34 45, 45 , 23xp,"
" 12de, 32, 34 45, 45, 23xp,"
easily but reject
容易但拒绝
" de12, 32, 34 45, 45 , 23xp,"
" de12, 32, 34 45, 45, 23xp,"
One problem is still there as you can see that in first case it will display " 12, 32, 34, 45, 23, " at the end where it has truncated "34 45" to 34. A special case may be added to handle this as error or ignore white space in the middle of token.
一个问题仍然存在,如您所见,在第一种情况下,它会在将“34 45”截断为 34 的末尾显示“12, 32, 34, 45, 23”。可以添加特殊情况来处理这是错误或忽略令牌中间的空格。
wchar_t in;
std::wstring seq;
std::vector<int> input;
std::wcout << L"Enter values : ";
while (std::wcin >> std::noskipws >> in)
{
if (L'\n' == in || (L',' == in))
{
if (!seq.empty()){
try{
input.push_back(std::stoi(seq));
}catch (std::exception e){
std::wcout << L"Bad input" << std::endl;
}
seq.clear();
}
if (L'\n' == in) break;
else continue;
}
seq.push_back(in);
}
std::wcout << L"Values entered : ";
std::copy(begin(input), end(input), std::ostream_iterator<int, wchar_t>(std::wcout, L", "));
std::cout << std::endl;