You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++程序动态分配数组始终设为大小1的问题求助

修复数字命理单词数值计算程序的循环输入问题

我给对数字命理感兴趣的朋友写了个单词数值计算程序,逻辑是先询问用户要计算的单词数量,以此动态分配存储单词的数组。第一次运行一切正常,但当选择“是”继续计算时,无论输入什么数字,数组大小始终被设为1——number变量一直保持1,用户每次都得重启程序才能正常使用。我计划后续优化代码,但现在想先修复这个运行问题。

原代码:

#include <iostream>
#include <string>
#include <sstream>

void clear()
{
    system("clear");
}

int main(int argc, char* argv[])
{
    int number{1};
    int total{0};
    int value{0};
    std::string number_str;
    std::string response;
    std::stringstream ss;
    bool isDigit;


    while (true)
    {
        clear();

        number = 1;
        total = 0;
        value = 0;
        number_str = "";
        response = "";
        isDigit = true;

        clear();
        std::cout << "How many words to evalute? (Default: 1):\n> ";
        //std::cin >> number;
        std::getline(std::cin, number_str);

        //std::cin.ignore();
        clear();

        for (int i = 0; i < number_str.size(); ++i)
        {
            if (!(std::isdigit(number_str[i])))
                isDigit = false;
                break;
        }

        if (isDigit)
        {
            if (number_str.empty()) {
                number = 1;
            } else {
                ss << number_str;
                ss >> number;
            }
        }


        if (std::isdigit(number)) {
            if (number <= 0) {
                number = 1;
            }
        }

        std::string* pPhrase = new std::string[number];
        int* pValue = new int[number]{}; // Initialized each element to 0

        for (int i = 0; i < number; ++i) // could replace "number" with "sizeof(pPhrase)/sizeof(pPhrase[0])"
        {
            (i == 0) ? std::cout << "Enter Word #" << i+1 << " (or type your full phrase):\n> " :
                                        std::cout << "Enter Word #" << i+1 << ":\n> ";
            std::cin >> pPhrase[i];

            for (char j : pPhrase[i])
            {
                value = 0;
                if (std::isalnum(j) && j != '0')
                {
                    if (std::isalpha(j))
                        j = std::tolower(j);

                    
                } else {
                    continue;
                }

                if (j == 'a' || j == 'i' || j == 'j'
                        || j == 'q' || j == 'y' || j == '1')
                    value += 1;

                if (j == 'b' || j == 'k' || j == 'r' || j == '2')
                    value += 2;

                if (j == 'c' || j == 'g' || j == 'l'
                        || j == 's' || j == '3')
                    value += 3;

                if (j == 'd' || j == 'm' || j == 't' || j == '4')
                    value += 4;

                if (j == 'e' || j == 'h' || j == 'n'
                        || j == 'x' || j == '5')
                    value += 5;

                if (j == 'u' || j == 'v' || j == 'w' || j == '6')
                    value += 6;

                if (j == 'o' || j == 'z' || j == '7')
                    value += 7;

                if (j == 'f' || j == 'p' || j == '8')
                    value += 8;
                
                pValue[i] += value;
                value = 0;
                std::cout << '\n';
                clear();
            }

        }

        
        std::cin.ignore();
        std::cin.clear();

        std::cout << "\n\n";


        for (int i = 0; i < number; ++i)
        {
            std::cout << "Value of \"" << pPhrase[i] << "\": " << pValue[i] << '\n';
            total += pValue[i];
        }

        std::cout << "Total value: " << total << "\n\nPress 'Enter' or 'Return' to Continue... ";

        //std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        //std::cin.clear();

        std::cout << "\n\n\nWould you like to evaluate another phrase? (Y/n):\n> ";
        std::getline(std::cin, response);

        delete[] pPhrase;
        delete[] pValue;


        if (response[0] == 'y' || response[0] == 'Y'
                || response.empty() || response[0] == ' ')
            continue;

        break;

    }

    std::cout << "Exiting...";
    try {
        //system("killall Terminal");
    } catch (std::exception& ex) {}

    std::cout << "\n\n\n";
    return 0;
}

关键修复点

  • 重置stringstream状态:每次使用ss转换字符串前,必须调用ss.clear()清空流的错误状态,再调用ss.str("")清空流内存储的内容——原代码第一次循环后ss处于EOF状态,后续写入新字符串也无法正确读取到number变量。
  • 修正数字检查逻辑:给数字检查循环里的if和break添加花括号,确保遍历整个字符串判断是否全为数字,原代码只会检查第一个字符就直接跳出循环。
  • 移除无效判断:删除std::isdigit(number)的错误判断,number是int类型,std::isdigit仅接收unsigned char类型参数,该判断毫无意义,直接检查number <= 0即可。
  • 补充缺失头文件:添加<limits>头文件,原代码使用std::numeric_limits但未包含该头文件,会导致编译错误。

修复后的完整代码:

#include <iostream>
#include <string>
#include <sstream>
#include <limits>

void clear()
{
    system("clear");
}

int main(int argc, char* argv[])
{
    int number{1};
    int total{0};
    int value{0};
    std::string number_str;
    std::string response;
    std::stringstream ss;
    bool isDigit;


    while (true)
    {
        clear();

        number = 1;
        total = 0;
        value = 0;
        number_str = "";
        response = "";
        isDigit = true;

        clear();
        std::cout << "How many words to evalute? (Default: 1):\n> ";
        std::getline(std::cin, number_str);

        clear();

        for (int i = 0; i < number_str.size(); ++i)
        {
            if (!(std::isdigit(static_cast<unsigned char>(number_str[i]))))
            {
                isDigit = false;
                break;
            }
        }

        if (isDigit)
        {
            if (number_str.empty()) {
                number = 1;
            } else {
                ss.clear();
                ss.str("");
                ss << number_str;
                ss >> number;
            }
        }

        if (number <= 0) {
            number = 1;
        }

        std::string* pPhrase = new std::string[number];
        int* pValue = new int[number]{};

        for (int i = 0; i < number; ++i)
        {
            (i == 0) ? std::cout << "Enter Word #" << i+1 << " (or type your full phrase):\n> " :
                                        std::cout << "Enter Word #" << i+1 << ":\n> ";
            std::cin >> pPhrase[i];

            for (char j : pPhrase[i])
            {
                value = 0;
                if (std::isalnum(static_cast<unsigned char>(j)) && j != '0')
                {
                    if (std::isalpha(static_cast<unsigned char>(j)))
                        j = std::tolower(static_cast<unsigned char>(j));
                } else {
                    continue;
                }

                if (j == 'a' || j == 'i' || j == 'j'
                        || j == 'q' || j == 'y' || j == '1')
                    value += 1;

                if (j == 'b' || j == 'k' || j == 'r' || j == '2')
                    value += 2;

                if (j == 'c' || j == 'g' || j == 'l'
                        || j == 's' || j == '3')
                    value += 3;

                if (j == 'd' || j == 'm' || j == 't' || j == '4')
                    value += 4;

                if (j == 'e' || j == 'h' || j == 'n'
                        || j == 'x' || j == '5')
                    value += 5;

                if (j == 'u' || j == 'v' || j == 'w' || j == '6')
                    value += 6;

                if (j == 'o' || j == 'z' || j == '7')
                    value += 7;

                if (j == 'f' || j == 'p' || j == '8')
                    value += 8;
                
                pValue[i] += value;
                value = 0;
                std::cout << '\n';
                clear();
            }

        }

        
        std::cin.ignore();
        std::cin.clear();

        std::cout << "\n\n";

        for (int i = 0; i < number; ++i)
        {
            std::cout << "Value of \"" << pPhrase[i] << "\": " << pValue[i] << '\n';
            total += pValue[i];
        }

        std::cout << "Total value: " << total << "\n\nPress 'Enter' or 'Return' to Continue... ";

        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

        std::cout << "\n\n\nWould you like to evaluate another phrase? (Y/n):\n> ";
        std::getline(std::cin, response);

        delete[] pPhrase;
        delete[] pValue;

        if (response[0] == 'y' || response[0] == 'Y'
                || response.empty() || response[0] == ' ')
            continue;

        break;

    }

    std::cout << "Exiting...";
    try {
        //system("killall Terminal");
    } catch (std::exception& ex) {}

    std::cout << "\n\n\n";
    return 0;
}

内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:33:34