Get()和peek()有助于存储大数

get() and peek() help for storing large numbers

本文关键字:存储 peek Get 有助于      更新时间:2023-10-16

我在使用cin.peek()和cin.get()函数时遇到了麻烦。我总是不知道怎么输入。基本上,我试图能够得到一串数字(可以比int长,这就是为什么它使用字符)插入到MyInt对象使用>>的重载。我写的MyInt类中有一个动态字符数组myNumber。resize函数就是这样做的,将动态数组的大小调整为新的大小。

我需要做两件事

  1. 忽略前导空格
  2. 停在下一个不是0-9的字符处。(空格、字母)

我有:

istream& operator>> (istream& s, MyInt& n)
// Overload for the input operator                                                                                             
{
  char c;             // For peeking                                                                                           
  int x;
  MyInt input;        // For storing                                                                                           
  unsigned int counter = 0; // counts # of stored digits                                                                       
  while (isspace(s.peek()))
  {
    c = s.get();
  }
  while (C2I(s.peek()) != -1)
  {
    x = C2I(s.get());
    input.myNumber[counter] = I2C(x);
    counter++;
    input.Resize(counter);
  }
  cout << "WHAH WHAH WEE WAHn";
  n = input;
}

Main调用了这个:

cout << "Enter first number: ";
cin >> x;
cout << "Enter second number: ";
cin >> y;
cout << "You entered:n";
cout << "  x = " << x << 'n';
cout << "  y = " << y << 'n';

下面是我得到的输出:

Enter first number: 14445678954333
WHAH WHAH WEE WAH
Enter second number: 1123567888999H
WHAH WHAH WEE WAH
You entered:
  x = 111111111111113
  y = 11111111111119

我是一个学生,这是"家庭作业"。就像所有的家庭作业一样,给我的都是一些我无法理解的不合逻辑的东西。这个是字符串类。这是工作中很小的一部分,但它就像我的眼中钉。

我会说在调试器中运行它,找出你搞砸数组的地方,我猜是调整大小。

因为你的输入和输出遵循一个模式。

14445678954333
111111111111113
1123567888999H
11111111111119

您长了1,第一个和最后一个数字匹配

为什么不总是使用std::string来读写你的数字呢?

那么你所需要的就是从MyInt <-> std::string 进行转换
class MyInt
{
    vector<int> Integers;
public:
    MyInt( const string& source )
    {
        for ( size_t i = 0; i < source.size(); ++i )
        {
            Integers.push_back( source[i] - '0' );
        }
    }
    MyInt()
    {
    }
};
istream& operator>> (istream& s, MyInt& n)
{
    string input;
    s >> input;
    n = input;
    return s;
}
int main()
{
    MyInt input;
    cout << "Enter first number: ";
    cin >> input;
    return 0;
}