0

正如问题所说,由于某种原因,我的程序没有以我目前无法识别的方式刷新输入或使用我的变量。这是一个家庭作业项目,我已经超出了我必须为此做的事情,现在我只想让程序真正工作:P

使查找更容易的详细信息:

该程序在第一次运行时完美执行。所有抛出都有效,只有正确的值( n > 0 )被接受并转换为二进制。

一旦我输入终止输入,程序就会进入一个循环,并且只要求再次终止,如下所示:

当我在我的 Linux 笔记本电脑上的 Netbeans 上运行这个程序时,在我输入终止值后程序崩溃了。在 Windows 上的 Visual C++ 上,它像刚才描述的那样进入循环。

在代码中,我尝试在程序重新启动时清除每个流并初始化每个新变量,但无济于事。我只是看不到我的错误。

我相信错误在于主要功能:

int main( void )
{
vector<int> store;
int terminate = 1;

do
{
    int    num   =  0;
    string input = "";

    if( cin.fail() )
    {
        cin.clear();
        cin.ignore( numeric_limits<streamsize>::max(), '\n' );
    }

    cout << "Please enter a natural number." << endl;
    readLine( input, num );

    cout << "\nThank you. Number is being processed..." << endl;
    workNum( num, store );

    line;
    cout << "Go again? 0 to terminate." << endl;
    cin >> terminate // No checking yet, just want it to work!

    cin.clear();
}while( terminate );

cin.get();
return 0;
}

或在读取数字的函数中:

void readLine( string &input, int &num )
{
    int buf = 1;
    stringstream ss;
    vec_sz size;

    if( ss.fail() )
 {
        ss.clear();
     ss.ignore( numeric_limits<streamsize>::max(), '\n' );
 }

    if( getline( cin, input ) )
    {
       size = input.size();
       for( int loop = 0; loop < size; ++loop )
           if( isalpha( input[loop] ) )
               throw domain_error( "Invalid Input." );

    ss << input;
    ss >> buf;

    if( buf <= 0 )
        throw domain_error( "Invalid Input." );

    num = buf;

    ss.clear();
    }
}
4

2 回答 2

2

当您调用cin >> terminate时,它将读取终止的值,但在输入流中将换行符留在它后面。当您调用时getline(cin, input),它会读取到换行符,这意味着它将获得一个空字符串。

您可以通过在以下添加以下内容来丢弃所有字符直到换行符cin >> terminate

cin.ignore(99, '\n');

或者避免混合operator >>getline

于 2010-04-25T12:28:47.773 回答
2

不要像 interjay 提到的那样将这些>>和运营商混为一谈。getline另外,如果你想清除你的代码,我认为它可以重写如下方式:

int main() {
   while (true) {
      std::cout << "Please enter a natural number" << std::endl;
      int num;
      std::cin >> num;

      // Exception handling here can be done easily
      // like this
      // if (!(std::cin >> num) || num < 0)
      //    throw std::domain_error("TROLOLOLO");

      std::cout << "Thank you. Number is being processed..." << std::endl;
      //workNum(num, store) here

      std::cout << "Go again? 0 to terminate." << std::endl;

      int terminate;
      std::cin >> terminate;
      if (terminate == 0) break;
   }
}
于 2010-04-25T12:44:05.663 回答