下面这段代码是“Essential c++”第四章的第一题,题目如下:
建立stack.h和stack.cpp,撰写main()函数,练习stack的所有公开接口,并加以编译执行。程序代码文件和main()都必须含入stack.h
代码如下:
stack.h:#include <string>
#include <vector>
using namespace std;class Stack {
public:    
bool   push( const string& );
        bool   pop ( string &elem );
bool   peek( string &elem );        bool   find(  const string &elem ) const;
int    count( const string &elem ) const; bool   empty() const { return _stack.empty(); }
bool   full()  const { return _stack.size() == _stack.max_size(); }
int    size()  const { return _stack.size(); }private:
vector<string> _stack;
};bool
Stack::pop( string &elem ) 
{
    if ( empty() )
         return false;    elem = _stack.back();
    _stack.pop_back(); 
    
    return true;
}bool
Stack::peek( string &elem ) 
{
    if ( empty() )
         return false;    elem = _stack.back();
    return true;
}bool
Stack::push( const string &elem ) 
{
    if ( full() )
         return false;    _stack.push_back( elem );
    return true;
}stack.cpp:#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include "stack.h"
using namespace std;void main()
{
    Stack st;
    string str; cout << "Please enter a series of strings.\n";
    while ( cin >> str &&  !st.full())
            st.push( str );    if ( st.empty() ) {
         cout << '\n' << "Oops: no strings were read -- bailing out\n ";
         return;
 }
         
    st.peek( str );
    if ( st.size() == 1 && str.empty() ) {
         cout << '\n' << "Oops: no strings were read -- bailing out\n ";
         return;
 }    cout << '\n' << "Read in " << st.size() << " strings!\n"
   << "The strings, in reverse order: \n";    while ( st.size() ) 
 if ( st.pop( str ))
         cout << str << ' ';

cout << '\n' << "There are now " << st.size() 
  << " elements in the stack!\n";
}问题:我在编译时有几个warning,执行的时候一直在从屏幕取词,总是跳不出while循环。请问是怎么回事。先谢过各位大侠了!

解决方案 »

  1.   

    改成
        while ( cin >> str &&  !st.empty())
                st.push( str );
    看看,我对string不是很熟
      

  2.   

    这样不行啊。
    这样的话while的条件一直为假,st.push(str)永远执行不了。
      

  3.   

    while ( cin >> str && str != "~~~~~eXit" )
                st.push( str );
    明白了吧?输入~~~~~eXit退出;
      

  4.   

    明白为什么了
    你的st是stack
    估计大家都和str看混了
    while ( cin >> str &&  !st.full())
                            ~~~~~
                st.push( str );
    你这里一只要等到stack满了才会停止输入
    你只要把stack的上限设置小一点就可以了
    或者如楼上所说
      

  5.   

    你申请的ST的大小是多少?ST何时才FULL啊。
      

  6.   

    这个是下载的源代码。我觉得很奇怪的是:代码中没有地方设置了stack的上限值。请问要在什么地方,怎样设这个上限值?
    谢谢!
      

  7.   

    stack好象有个reserve()方法可以设置,记不太请了,你看一下把。