问题描述
我对每个人都有一个简单的问题.我正在尝试编写一个简单的代码来从用户输入中提取数字并将其保存到int数组中,但是我很难确定如何使它工作.下面显示的代码适用于一位数字,但不适用于一位数字以上的数字.
I have a quick question for everyone. I'm trying to write a simple code to extract numbers form user input and save them to an int array, but I'm having a hard time wrapping my mind around how to make it work. The code shown below works well for single-digit numbers, but not so much for numbers with more than 1 digit.
例如,如果用户输入:1,2,3,4,50,60,这就是我得到的:
For instance, if user enters: 1,2,3,4,50,60 here is what I get:
Enter numbers (must be comma delimited): 1,2,3,4,50,60
My numbers are: 12345060
My parsed numbers are: 1
My parsed numbers are: 2
My parsed numbers are: 3
My parsed numbers are: 4
My parsed numbers are: 5
My parsed numbers are: 0
问题:如何修改这段简单的代码以准确捕获超过1位的数字?在此先感谢!
Question: how can I modify this simple piece of code to accurately capture numbers with more than 1 digit? Thanks in advance!!
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
// set up some variables
int numbers[100];
int main() {
// Enter numbers (comma delimited). Ex: 1,2,3,4,50,60<return>
cout << endl << endl << "Enter numbers (must be comma delimited): ";
string nums_in;
getline(cin, nums_in);
nums_in.erase(remove(nums_in.begin(), nums_in.end(), ','), nums_in.end()); // remove the unwanted commas
cout << "My numbers are: " << nums_in << endl;
// convert each char into int
for (int o = 0; o < 6; o++) {
istringstream buf(nums_in.substr(o,1));
buf >> numbers[o];
cout << "My parsed numbers are: " << numbers[o] << endl;
}
cout << endl << endl;
cout << "Done." << endl;
return 0;
}
推荐答案
使用 std :: getline 读取字符串中的整行,然后使用 std :: istringstream 提取单个数字并跳过逗号.
This task can be easily done using std::getline to read the entire line in a string and then parse that string using a std::istringstream to extract the individual numbers and skip the commas.
#include <iostream>
#include <sstream>
#include <vector>
using std::cout;
int main() {
// Enter numbers (comma delimited). Ex: 1,2,3,4,50,60<return>
cout << "\nEnter numbers (must be comma delimited): ";
int x;
std::vector<int> v;
std::string str_in;
// read the whole line then use a stringstream buffer to extract the numbers
std::getline(std::cin, str_in);
std::istringstream str_buf{str_in};
while ( str_buf >> x ) {
v.push_back(x);
// If the next char in input is a comma, extract it. std::ws discards whitespace
if ( ( str_buf >> std::ws).peek() == ',' )
str_buf.ignore();
}
cout << "\nMy parsed numbers are:\n";
for ( int i : v ) {
cout << i << '\n';
}
cout << "\nDone.\n";
return 0;
}
这篇关于在C ++中解析逗号分隔的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!