我有一个简短的问题要问大家。我正在尝试编写一个简单的代码来从用户输入中提取数字并将它们保存到一个 int 数组中,但是我很难思考如何让它工作。下面显示的代码适用于一位数,但不适用于多于 1 位的数字。
例如,如果用户输入:1,2,3,4,50,60 这是我得到的:
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
问题:如何修改这段简单的代码来准确捕获多于一位的数字?提前致谢!!
#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;
}
最佳答案
在您的程序中,您首先删除了输入字符串中“不需要的”逗号,然后遇到无法再区分输入行中的数字的问题。所以看起来好像这些逗号毕竟不是不需要的。解决方案是在不先删除逗号的情况下逐步解析字符串,因为您需要它们来拆分输入字符串。这是一个例子。
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <vector>
int main() {
// Enter numbers (comma delimited). Ex: 1,2,3,4,50,60<return>
std::cout << std::endl << std::endl << "Enter numbers (must be comma delimited): ";
std::string nums_in;
std::getline(std::cin, nums_in);
// Now parse
std::vector<int> data;
std::istringstream buf(nums_in);
while (!buf.eof()) {
int this_number;
buf >> this_number;
if (buf.bad()) {
std::cerr << "Number formatting error!\n";
return 1;
}
data.push_back(this_number);
char comma = 0;
buf >> comma;
if (!buf.eof()) {
if (buf.fail()) {
std::cerr << "Could not read comma.\n";
return 1;
}
if (comma!=',') {
std::cerr << "Found no comma but '" << comma << "' instead !\n";
return 1;
}
}
}
std::cout << "My numbers are:";
for (auto a : data) {
std::cout << " " << a;
}
std::cout << std::endl;
std::cout << "Done." << std::endl;
return 0;
}
请注意,我没有使用“using namespace std;”因为它被认为是不好的风格。此外,我使用 C++11 功能打印出值并使用 vector 存储数字 - 在您的代码中,在一行中键入 200 个数字会导致崩溃(或其他不良行为)。最后,解析错误处理还没有完成。使其完整和正确留作练习。基于 istringstream 的方法的替代方法是首先用逗号分隔行,然后使用 istringstreams 分别读取所有数字。
顺便说一下,你的问题太实用了,它更适合标准的 stackexchange 站点——与计算机科学的联系非常薄弱。
关于c++ - 在 C++ 中解析逗号分隔的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35684285/