Get()和peek()有助于存储大数
get() and peek() help for storing large numbers
我在使用cin.peek()和cin.get()函数时遇到了麻烦。我总是不知道怎么输入。基本上,我试图能够得到一串数字(可以比int长,这就是为什么它使用字符)插入到MyInt对象使用>>的重载。我写的MyInt类中有一个动态字符数组myNumber。resize函数就是这样做的,将动态数组的大小调整为新的大小。
我需要做两件事
- 忽略前导空格
- 停在下一个不是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;
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 使用std::istream::peek()总是安全的吗
- 添加存储在向量中的大整数的函数出现问题
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在std::vector上存储带有模板的类实例
- 谷歌测试中的期望值存储在哪里
- 为什么C中的通用链表中存储的数据已损坏
- Get()和peek()有助于存储大数