如何使用队列将字符串转换为大写?

问题描述

#include<iostream>
#include<queue>
#include<string> // probally not needed
#include<cctype>
using namespace std;
int main()
{
queue <string> str; // i created some kind of vector queue
cout << "Please enter a string." << endl;
string temp; 
cin >> temp; // grabs the string
if(temp != "") // checks if string is empty
{
 str.push(temp); // pushes it onto queue
 for(int i = 0; i < temp.size(); i++) // suppose to go through 
 //each element in queue
    {
       //str.pop(temp); /pops an element as requied by assignment
        toupper(i); // suppose to turn each letter upper case
    }
}
else 
{
    exit(0); // exits the program if string is empty
}
cout << temp; // suppose to display queue,that should be in 
//upper case form.

return 0;
}

我对编程还是很陌生,我不知道将队列实现为字符串。问题是 for 循环没有遍历每个字母,因此 (toupper()) 不能将它们大写。

提示:“编写一个程序,从用户那里获取一个句子(字符串)并将其放入一个字符队列中。然后程序应该将每个字符出列,将其转换为大写并将结果存储为一个句子(字符串) . 打印此过程的结果”。

解决方法

您可以通过以下方式执行此操作。

#include<iostream>
#include<queue>
#include<string> // probally not needed
#include<cctype>
using namespace std;
int main()
{
    queue <char> str; //make it char queue
    cout << "Please enter a string." << endl;
    string temp,result = ""; 
    getline (cin,temp); //grabs string,including spaces
    if(temp != "") // checks if string is empty
    {
        // push each character into queue
        for(int i = 0; i < temp.size(); i++) // suppose to go through 
        {
            str.push(temp[i]);
        }
        while(!str.empty()) //take a char from queue and do the task pop them.
        {
            char tm = str.front();
            str.pop();
            tm = tm-32; // making lower to upper
            result = result+tm;
        }
         
    }
    else 
    {
        exit(0); // exits the program if string is empty
    }
    cout << result; // suppose to display queue,that should be in 
    //upper case form.
    
    return 0;
}