2

我已经制作了一个程序,它接受用户输入的单词,将它们转换为数字,运行计算,然后将它们转换回单词,很简单,但是我的代码有错误。

每当我尝试输入一百或更高的值时,我都会得到输出“零”。(很可能意味着我试图转换的数字为零,而它不应该是。)

出于这个原因,我认为问题出在计算函数“write_value”中,但是我不确定是什么。

过去几个小时我一直在这里,所以它可能是一些我没有看到的小东西,但它可能有几件事,所以与其浪费更多时间,我想我会在这里发布更多有经验的人去看看。

提前感谢您的帮助。^^

示例输入为:one_hundred_forty_four + two_hundred_thirty_eight

正确输出:three_hundred_eighty_two

电流输出:零

当前代码:

using namespace std;

/**
 * Map units digits into words
 * 
 */
string units[] = {
    "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
    "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
    "seventeen", "eighteen", "nineteen"
};

/**
 * Map tens digits into words
 */
string tens[] = {
    "", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};

/**
 * Splits a string into components
 * 
 * @param words array for the components (assumed large enough)
 * @param base the string to split
 * @param separator the separator character
 * @return pointer to the first unused element in the array
 */
string* split(string* words, string base, char separator) {
    string* result = words;
    istringstream input(base);
    string token;
    while (getline(input, token, separator)) {
        if (token.length() > 0 && token != "and") {
            if (token == "hundred") {
                *--result += "_hundred";
                *result++;
            } else if (token == "thousand") {
                *--result += "_thousand";
                *result++;
            } else if (token == "million") {
                *--result += "_million";
                *result++;
            } else {
                *result++ = token;
            }
        }
    }
    return result;
}

/**
 * Joins an array of component strings into a single string
 * 
 * @param words pointer to first component
 * @param end pointer to the component beyond the last
 * @param separator the separator character
 * @return the joined string
 */
string join(string* words, string* end, char separator) {
    string result;
    if (words < end) {
        result.append(*words);
        for (string* w = words + 1; w < end; w++) {
            result.append(separator + *w);
        }
    }
    return result;
}

/**
 * Writes number words into an array
 * 
 * @param words array to store the words
 * @param n the number to write
 * @return pointer to the first unused element
 */
string* write_value(string* words, int n) {
    string* result = words;


    int t = (n % 100) / 10;
    int u = (n % 10);

    if (t == 1) { // fixes teens
        t--;
        u += 10;
    }
    if (t) {
        *result++ = tens[t];
    }
    if (u) {
        *result++ = units[u];
    }
    return result;
}

/**
 * Reads an array of number words
 * 
 * @param words the number words to read
 * @param end pointer to the word beyond the last
 * @return the value read
 */
int read_value(string* words, string* end) {
    int result = 0;
    string* w = words;

    for (int i = 1; i < 10; i++) {
        if (*w == tens[i]) {
            result += 10 * i;
            w += 1;
            break;
        }
    }
    for (int i = 1; i < 20; i++) {
        if (*w == units[i]) {
            result += i;
            break;
        }
    }
    return result;
}

/**
 * Writes a number word string
 * 
 * @param n the number to write
 * @return the word string
 */
string Wordnum::write_number(int n) {
    string result;
    string words[20]; 
    string* end;
    if (n == 0) {
        result = "zero";
    } else if (n < 0) {
        end = write_value(words, -n);
        result = "negative_" + join(words, end, '_');
    } else {

        if (n > 100) {
            end = write_value(words, n);
            result = join(words, end, '_') + "hundred_";
        } else if (n > 1000) {
            end = write_value(words, n);
            result = join(words, end, '_') + "thousand_";
        } else if (n > 1000000) {
            end = write_value(words, n);
            result = join(words, end, '_') + "million_";
        }
        end = write_value(words, n);
        result = join(words, end, '_');
    }
    return result;
}

/**
 * Reads a number word string
 * 
 * @param n the string to read
 * @return the value read
 */
int Wordnum::read_number(string n) {
    int result;
    string words[20]; 
    for (int i = 0; i < n.length(); i++) {
        n[i] = tolower(n[i]);
        if (n[i] == '-') n[i] = '_';
    }
    string* end = split(words, n, '_');

    if (end == words || words[0] == "zero") {
        result = 0;
    } else if (words[0] == "negative") {
        result = -read_value(words + 1, end);
    } else {
        result = read_value(words, end);

        for (int i = 0; i < n.length(); i++) {
            if (words[i] == "hundred") {
                result = read_value(words - 1, end) * 100;
                break;
            } else if (words[i] == "thousand") {
                result = read_value(words - 1, end) * 1000;
                break;
            } else if (words[i] == "million") {
                result = read_value(words - 1, end) * 1000000;
                break;
            }
        }
    }
    return result;
}

/**
 * Inserts a Wordnum into an output stream as a word string
 * 
 * @param os the stream to insert into
 * @param n the value to insert
 * @return the modified stream
 */
ostream& operator<<(ostream& os, const Wordnum& n) {
    return os << Wordnum::write_number(n.value_);
}

/**
 * Extracts a Wordnum in word string form from an input stream
 * 
 * @param is the stream to extract from
 * @param n the value to assign
 * @return the modified stream
 */
istream& operator>>(istream& is, Wordnum& n) {
    string text;
    if (is >> text) {
        n.value_ = Wordnum::read_number(text);
    }
    return is;
}

头文件:

 #ifndef WORDNUM_H_
#define WORDNUM_H_

#include <string>
#include <istream>
#include <ostream>

/**
 * A class to read and write numbers in word form
 */

class Wordnum {
public:

    /**
     * Writes a number word string
     * 
     * @param n the number to write
     * @return the word string
     */
    static std::string write_number(int n);

    /**
     * Reads a number word string
     * 
     * @param n the string to read
     * @return the value read
     */
    static int read_number(std::string n);

    /**
     * Creates a new Wordnum for a given value
     * 
     * @param n the value of the number
     */
    Wordnum(int n = 0) {
        value_ = n;
    }

    /**
     * Creates a new Wordnum from a word string
     * 
     * @param n the value of the number
     */
    Wordnum(std::string n) {
        value_ = read_number(n);
    }

    /**
     * Creates a new Wordnum as a copy of another
     * 
     * @param n the value to copy
     */
    Wordnum(const Wordnum& n) {
        value_ = n.value_;
    }

    /**
     * Makes this equivalent to n
     * 
     * @param n the value to copy
     * @return the modified Wordnum
     */
    Wordnum& operator =(const Wordnum& n) {
        value_ = n.value_;
        return *this;
    }

    /**
     * Converts a Wordnum to an int
     * 
     * @return the value as an int
     */
    operator int () const {
        return value_;
    }

    /**
     * Converts a Wordnum to a string
     * 
     * @return the value as a word string
     */
    operator std::string() const {
        return write_number(value_);
    }

    /**
     * Inserts a Wordnum into an output stream as a word string
     * 
     * @param os the stream to insert into
     * @param n the value to insert
     * @return the modified stream
     */
    friend std::ostream& operator <<(std::ostream &os, const Wordnum& n);

    /**
     * Extracts a Wordnum in word string form from an input stream
     * 
     * @param is the stream to extract from
     * @param n the value to assign
     * @return the modified stream
     */
    friend std::istream& operator >>(std::istream &is, Wordnum& n);

    /**
     * Returns sum of n1 and n2
     */
    friend Wordnum operator +(const Wordnum& n1, const Wordnum& n2) {
        return Wordnum(n1.value_ + n2.value_);
    }

    /**
     * Returns difference of n1 and n2
     */
    friend Wordnum operator -(const Wordnum& n1, const Wordnum& n2) {
        return Wordnum(n1.value_ - n2.value_);
    }

    /**
     * Returns product of n1 and n2
     */
    friend Wordnum operator *(const Wordnum& n1, const Wordnum& n2) {
        return Wordnum(n1.value_ * n2.value_);
    }

    /**
     * Returns quotient of n1 and n2
     */
    friend Wordnum operator /(const Wordnum& n1, const Wordnum& n2) {
        return Wordnum(n1.value_ / n2.value_);
    }

private:
    int value_;
};

#endif
4

1 回答 1

0

从字符转换为整数并不简单。
char*(cstring) 是一个 char 数组,其中每个元素的大小为一个字节(8 位)

一个整数是 4 个字节(32 位),因此,要正确地将 char 转换为 int,您必须用 char 填充 4 个字节中的每一个。换句话说,你需要 4 个字符来创建一个 int。

好像这还不够,还需要考虑另一个因素。需要考虑系统的字节顺序 (我将由您自行查找)。

字节序决定了您的系统如何存储数据。例如,在一个 16 位整数中,假设您存储数字 2,您的系统可以通过以下两种方式之一存储它:

方式1:00000010 00000000

方式2:00000000 00000010

由于 16 位整数存储在 2 个字节中,因此它可以从右到左或从左到右。 是一张图片。

这是进行字节序检查并将 char* (cstring) 转换为 int (32 位整数) 所需的代码

bool isBigEndian(){
    int a = 1;
    return !((char*)&a)[0];
}

int convertToInt(char *charArr, int len){          //len should be <= 4
    int a = 0;
    if(!isBigEndian())
        for(int i = 0; i < len; i++)
            ((char*)&a)[i] = charArr[i];
    else
        for(int i = 0; i < len; i++)
            ((char*)&a)[3-i] = charArr[i];
    return a;
}

因为代码将适用于大小为 4 或更小的 char* 数组,所以任何其他内容都不起作用,因为 int 不能容纳超过 4 个字节。我建议在查看代码之前先查看大端与小端,这样会更有意义。如果您对这是如何完成的有一个直觉,您可以转换为常规 int 以外的类型,您可以转换为 Uint16(16 位)或 Uint8(8 位;一次存储一个字符的完美大小;)

我希望你现在已经解决了这个问题,如果没有,希望这会有所帮助。

于 2014-02-19T06:55:54.397 回答