【问题标题】:C++: reading a string, converting to dynamic int arrayC ++:读取字符串,转换为动态 int 数组
【发布时间】:2013-11-28 08:50:40
【问题描述】:

我正在编写一个程序,要求用户输入一个非常大的 int(比 int 可以处理的类型大得多)。当从用户那里收到这个 int 时,它被存储在一个字符串中。然后,我想将此字符串转换为 int 数组(我使用的是动态 int 数组)。编译并运行程序后,我得到没有意义的值。我的 int 数组的值似乎是随机的乱码。我不明白为什么会这样——看起来我的循环在转换过程中并没有越界。请帮忙。创建一个 int 数组的目的是想出方法来加、减、乘和比较非常大的 int 值。为了明确我打算做什么:假设用户输入“12345”。我想将此字符串值存储到一个长度为 5 的 int 数组中,每个元素对应于 int 中的下一个数字。

大整数.h

#ifndef H_largeIntegers
#define H_largeIntegers
#include <iostream>
#include <string>

class largeIntegers
{
private: 

    void readInteger();
    // reads integer

public:

    std::string s_integer;
    int* integer;
    int length;

    largeIntegers();
    // default constructor

    void outputInteger();
    // outputs integer
};
#endif

大整数.cpp

#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;

largeIntegers::largeIntegers()
{
    readInteger();
}

void largeIntegers::readInteger()
{
    int i = 0,j = 0, k;

    cout << "Enter large integer: ";
    cin >> s_integer;

    for (; s_integer[i] != '\0'; i++);

    length = i;
    int* integer = new int[i];

    k = 0;
    for (j = i - 1; j >= 0; j--)
        integer[j] = s_integer[k++] - 48;
}

void largeIntegers::outputInteger()
{
    for (int i = length - 1; i >= 0; i--)
        cout << integer[i];
}

用户.cpp

#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;

int main()
{
    largeIntegers a;
    cout << a.length << endl << endl;
    cout << a.integer[0] << endl << a.integer[1] << endl;
    a.outputInteger();
    cout << endl << endl;

    return 0;
}

出于调试目的,我故意将标头中的变量公开。编译后我在控制台的输出是:

输入大整数:111

3

952402760

1096565083

10966961571096565083952402760

【问题讨论】:

  • long long int还要大?然后您可能需要检查诸如GMP 之类的库。
  • @JoachimPileborg 我忘了说这是我在第一门 C++ 课程中的家庭作业。 int 的大小将大于 C++ 提供的最大长度。此赋值的目的是使用动态 int 数组,以便对大整数值执行加法、减法等操作。

标签: c++ arrays dynamic integer int


【解决方案1】:

这就是问题

int* integer = new int[i];

改成

integer = new int[i];

您的版本声明了一个 local 变量,该变量恰好与您的类变量同名。容易犯错误。

【讨论】:

  • 有人应该说显而易见的:更好的是......使用std::vector&lt;int&gt;(或char - 大到足以容纳0-9位数的值)。
【解决方案2】:

此外,使用 std::vector 和 std::getline 等标准工具可以使您的代码更加简洁,避免您遇到的问题,并解决您现在调用 readInterger 两次时遇到的内存泄漏:

void largeIntegers::readInteger()
{
  cout << "Enter large integer: ";
  std::getline(std::cin, s_integer);
  integer = std::vector(s_integer.size());

  //your last loop to fill the array probably can be replaced by std::transform

}

【讨论】:

    猜你喜欢
    • 2016-11-18
    • 2016-08-13
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 2016-11-14
    • 2021-12-21
    • 2016-08-14
    • 1970-01-01
    相关资源
    最近更新 更多