[英]Convert int to an int array C++
给定用户的输入(例如 123456),您必须将输入 int 转换为 int 数组(例如 {1, 2, 3, 4, 5, 6}.
我想知道,这怎么能做到? 我从 function 开始计算输入的数字,并用数字数量初始化一个数组。
go 还有另一种更简单的方法吗?
这是我到目前为止所拥有的:
#include <iostream>
using namespace std;
int main()
{
int n, counter = 0;
cin >> n;
while (n != 1)
{
n = n / 10;
counter++;
}
counter += 1;
int arr[counter];
return 0;
}
让我解决这个问题有点矫枉过正,但实际上会教你各种 C++ 构造,而不是你现在正在做的“C 加上一点语法糖”。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main( int argc, char * argv[] )
{
if ( argc != 2 )
{
std::cout << "Enter *one* number.\n";
return 1;
}
// Don't work with C arrays any more than you absolutely must.
// Initializing a variable with those curly braces is the
// modern C++ way of initialization. The older way using ()
// had some issues (like the "most vexing parse" problem).
std::string input { argv[1] };
// Initialize a vector of int with the elements of input.
// If you need the elements in reverse order, just use
// std::rbegin and std::rend.
std::vector<int> output { std::begin( input ), std::end( input ) };
// The elements of output right now have a value depending on
// the character encoding, i.e. they refer to the *character
// value* of the digit, not the *integer* value. You could
// call `std::stoi` on each, or you can substract the encoded
// value for the letter '0', because the standard guarantees
// that '0' through '9' are encoded with consecutive values.
// This is NOT true for letters!
// The part starting at [] is called a "lambda", and it is a
// very nifty feature in conjunction with <algorithm> that you
// should study at some point (right after you learned what a
// 'functor' is, which is probably a bit down the road yet).
// Think of it as a way to define a local function without
// giving it a name.
std::for_each( output.begin(), output.end(), [](int & i){ i -= '0'; } );
// Prefer range-for over indexed for.
for ( auto & i : output )
{
std::cout << i << "\n";
}
return 0;
}
不过,该解决方案在高级 C++ 功能上有点重。
第二个更简单(没有<algorithm>
或 lambdas),但显示了正确的输入错误处理,并且仍然避免对数字进行手动算术:
#include <iostream>
#include <string>
#include <vector>
int main()
{
int input;
while ( ! ( std::cin >> input ) )
{
std::cout << "Enter a number.\n";
std::cin.clear();
std::cin.ignore();
}
std::string number { std::to_string( input ) };
// You *can* reserve space in the vector beforehand,
// but unless you know you will be pushing a LOT of
// values, I would not bother. (Also, there are a
// couple of mistakes you could make if you try.)
std::vector<int> output;
for ( auto & c : number )
{
output.push_back( c - '0' );
}
for ( auto & i : output )
{
std::cout << i << "\n";
}
}
首先,您必须计算数字中有多少位的循环仅在最左边的数字是1
时才有效:
while (n != 1) // what if it's 2-9 instead?
{
n = n / 10;
counter++;
}
counter += 1;
正确的计算是
do {
n /= 10; // same as n = n / 10
++counter;
} while(n);
您必须将输入 int 转换为 int 数组
使用标准 C++ 很难满足此要求,因为在编译时必须知道 arrays 的大小。 一些编译器支持可变长度 Arrays ,但使用它们会使您的程序不可移植。 用于创建仅在运行时知道大小的类数组容器的工具是 class 模板std::vector
。 在这种情况下,您想使用std::vector<int>
。 我已将数字计数部分放在单独的 function 中:
#include <iostream>
#include <vector>
int count_digits(int number) {
int counter = 0;
do {
number /= 10;
++counter;
} while (number);
return counter;
}
int main() {
int n;
if (!(std::cin >> n)) return EXIT_FAILURE;
// instead of int arr[ count_digits(n) ]; use a vector<int>:
std::vector<int> arr( count_digits(n) );
// fill the vector starting from the end:
for(size_t idx = arr.size(); idx--;) {
arr[idx] = n % 10; // extract the least significant digit
n /= 10;
}
// print the result using an old-school loop:
for(size_t idx = 0; idx < arr.size(); ++idx) {
std::cout << arr[idx] << '\n';
}
// print the result using a range based for-loop:
for(int value : arr) {
std::cout << value << '\n';
}
}
或者,使用反向迭代器来填充vector
:
for(auto it = arr.rbegin(); it != arr.rend(); ++it) {
*it = n % 10;
n /= 10;
}
您还可以使用标准 function std::to_string
将int
转换为std::string
(或直接从用户读取值作为std::string
)。
一旦你有了一个std::string
,你就可以通过转换轻松地填充vector<int>
。
例子:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
int main() {
int n;
if (!(std::cin >> n)) return EXIT_FAILURE;
auto as_str = std::to_string(n);
std::vector<int> arr(as_str.size()); // create it big enough to hold all digits
// transform each character in the string and put the result in arr:
std::ranges::transform(as_str, arr.begin(), [](char ch) { return ch - '0'; });
// print the result:
for (int x : arr) std::cout << x << '\n';
}
对您来说最简单的方法是使用相同的循环来计算位数以保存它(使用 n%10 会给您数字中的最后一位)。 你也不应该使用int arr[counter];
,因为在 c++ 中不支持可变长度 arrays ,即使代码已实际编译。 您应该使用在堆中分配的数组int* arr = new int[counter];
这是我猜的最简单的方法!
int integer_length(int number){
return trunc(log10(number)) + 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.