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

使用for循环时C++ STL Queue的pop方法无法正常工作

解决STL队列处理数字字符串的问题

看起来你在把输入的数字字符串转成STL队列元素的过程中遇到了小问题,我先帮你梳理下代码里的问题,再给出修正后的版本。

首先先看你提供的代码:

#include<iostream>
#include<queue>
#include<string>
//#include<cctype>
using namespace std;
//int to_words(int i);
//int to_words_one(queue<int> &q);
int main() {
 queue<int> q;
 string s;
 cout << "Enter a number not more than 12 digits : ";
 getline(cin, s, '\n...'); // 这里存在错误
 // 缺少将字符串转成队列元素的核心逻辑
 return 0;
}

代码里的核心问题

  • getline参数错误:getline的第三个参数只能是单个字符,你写的'\n...'是无效的。实际上默认情况下getline就会以换行符作为输入结束标志,完全可以省略这个参数。
  • 缺失字符串转队列的逻辑:还没实现把输入字符串中的每个数字字符转成int类型并推入队列的步骤。

修正后的完整代码

#include<iostream>
#include<queue>
#include<string>
#include<cctype> // 需要用到isdigit函数判断字符是否为数字
using namespace std;

int main() {
 queue<int> q;
 string s;
 cout << "Enter a number not more than 12 digits : ";
 getline(cin, s); // 修正getline用法,默认以换行符结束输入

 // 遍历字符串的每个字符,转成数字推入队列
 for(char c : s) {
     if(isdigit(c)) { // 过滤非数字字符,避免错误转换
         int num = c - '0'; // 字符转数字:ASCII码中'0'-'9'连续,减去'0'的ASCII值得到对应数字
         q.push(num);
     }
 }

 // 展示队列中的元素
 cout << "Queue elements: ";
 while(!q.empty()) {
     cout << q.front() << " ";
     q.pop(); // 取出元素后弹出队首,避免无限循环
 }
 cout << endl;

 return 0;
}

关键细节说明

  1. 字符转数字的原理:ASCII编码里,'0'到'9'的十进制值是连续的(48到57),所以用字符c减去'0'就能得到对应的int数字。
  2. isdigit的作用:过滤输入中可能混入的非数字字符,保证转换的安全性。
  3. 队列的遍历方式:队列是先进先出结构,需要用front()获取队首元素,pop()弹出队首元素,直到队列为空。

如果你之前注释掉的to_words等函数是用来实现数字转英文单词的功能,可以基于这个修正后的代码继续扩展。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:31:36