[英]C++ How to convert what I thought was a string into an int? Trying to use stoi, but will use whatever works
我有一个所有数字的字符串变量,我将其解析为一个名为 hugeInt 的数组。 在循环中执行此操作,我一次从字符串中取出一个数字并尝试放入数组中。 我已经尝试了下面直接使用 std::stoi 的代码,它给了我一个错误,我认为它是一个字符串。 所以我也尝试使用const char *digit = strInt[j].c_str()
转换数字,但这也给了我一个错误。 那么我如何从一个真正的字符串中得到一个我认为是一个字符串(这是一个数字)来转换为一个 int。 下面的代码。 我的.h 文件
// HugeInteger.h
#ifndef HUGEINTEGER_H
#define HUGEINTEGER_H
#include <array>
class HugeInteger {
private:
static const int SIZE = 40;
std::array<short int,SIZE> hugeInt;
public:
HugeInteger(long = 0);
HugeInteger(std::string strInt);
void displayHugeInt();
};
#endif
我的实现代码
// HugeInteger.cpp
#include <iostream>
#include <stdexcept>
#include "HugeInteger.h"
HugeInteger::HugeInteger(long int num) {
for (short &element : hugeInt) {
element = 0;
}
for (int i = SIZE-1; i >= 0; i--) {
hugeInt[i] = num % 10;
num /= 10;
if (num == 0) {
break;
}
}
}
HugeInteger::HugeInteger(std::string strInt) {
for (short &element : hugeInt) {
element = 0;
}
if (strInt.length() > 40) {
throw std::invalid_argument("String integer is over 40 digits - too large.");
}
for (int i = SIZE-1, j = strInt.length()-1; j >= 0; i--, j--) {
if (isdigit(strInt[j])) {
hugeInt[i] = std::stoi(strInt[j]);
}
else {
throw std::invalid_argument("String integer has non digit characters.");
}
}
}
void HugeInteger::displayHugeInt() {
bool displayStarted = false;
for (short &element : hugeInt) {
if (!displayStarted) {
if (element == 0) {
continue;
}
else {
std::cout << element;
displayStarted = true;
}
}
else {
std::cout << element;
}
}
std::cout << std::endl;
}
问题出在 for 循环中的第二个构造函数(用于字符串)中,其中hugeInt[i] = std::stoi(strInt[j]);
是。 欢迎和赞赏任何帮助或建议。
strInt[j]
是char
,而不是std::string
。 我们不能std::stoi
单个字符,但由于我们知道它是一个数字(感谢isdigit(strInt[j])
),我们可以像赫克和
hugeInt[i] = strInt[j] - '0';
获取数字的值,因为 C++ 保证所有数字都被编码为从'0'
上升并且是连续的。 这意味着'0'
- '0'
将为 0。 '1'
- '0'
将为 1。 '2'
- '0'
将为 2,依此类推。
实际上,由于strInt[j]
是一个 ch,我不得不使用不同的字符串构造函数。 这个编译并正确运行hugeInt[i] = std::stoi(std::string(1,strInt[j]));
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.