-1

我一直在编写一个示例程序来比较一些算法的运行时间,这个程序给我带来了一些麻烦。出于某种原因,整个程序的各个部分都随机跳过了 cin / cout,我不完全确定为什么。这是代码,有问题的行已注释。find_element 已被注释掉以进行调试,但也不起作用。任何建议都会很棒!

#include <iostream>
#include <vector>

using namespace std;

void sort_vect( vector< int >& );
// int find_element( vector< int > );
void print_vect( vector< int > );

int main()
{
    vector< int > int_vect;
    int input;
    int result;

    char garbage;

    cout << "Enter a number into the vector (Q to quit) > ";

    while(cin >> input && input != 'Q' && input != 'q')
    {
        int_vect.push_back(input);
        cout << "> ";
    }

    // The following doesn't help
    // cin >> garbage;
    // cout << "Garbage : " << garbage << endl;

    if (int_vect.size() == 0)
    {
        cout << "Vector empty" << endl;
        return 1;
    }

    sort_vect(int_vect);
    print_vect(int_vect);

    cout << "What value do you want > ";
    cin >> input;   

    cout << "Result : " << int_vect[input-1] << endl;

    return 0;
} // main()

void sort_vect( vector< int >& int_vect)
{
    vector< int >::iterator vect_iterator;
    vector< int >::iterator temp_iterator;

    int temp_store = NULL;

    for(vect_iterator = int_vect.begin(); vect_iterator != int_vect.end(); vect_iterator++)
    {
        for (temp_iterator = vect_iterator; temp_iterator != int_vect.begin(); temp_iterator--)
        {
            while(*temp_iterator < *(temp_iterator-1))
            {
                temp_store = *temp_iterator;
                *temp_iterator = *(temp_iterator-1);
                *(temp_iterator-1) = temp_store;
            }
        }
    }

    cout << "Vector sorted." << endl << endl;
}

// int find_element( vector< int > int_vect)
// {
//  int input;
//  char garbage;
//  
//  cout << "Enter value to be returned (5 = 5th smallest) > ";
//  cin >> input;
//  cout << "Value for input : " << input << endl;
//      
//  return int_vect[input-1];
// }

void print_vect( vector< int > int_vect )
{
    vector< int >::iterator vect_iterator = int_vect.begin();

    while(vect_iterator != int_vect.end())
    {
        cout << *vect_iterator << endl;
        vect_iterator++;
    }
} // print_vect()

根据请求,输出(注意:输入错误,因为我忘记正确使用输入作为索引,但目前这不是问题):

Enter a number into the vector (Q to quit) > 1
> 2
> 4
> 6
> 5
> 3
> 4
> q
Vector sorted.

1
2
3
4
4
5
6
What value do you want > Result : 4
4

1 回答 1

0

您的代码跳过第二个输入的原因是您终止第一个输入循环的方式。

您的第一个循环终止不是因为您检测到用户输入了“q”,而是因为“q”不是一个有效的整数。任何字母、'q'、'x'、'z' 或任何东西都会停止你的循环。

尝试从字母中读取整数会导致cin. 一旦发生该错误,cin将不会再读取任何内容,因此它会“跳过”剩余的输入。

要查看是这种情况,请尝试更改您的代码,以便输入 -1 退出,如下所示

cout << "Enter a number into the vector (-1 to quit) > ";

while(cin >> input && input >= 0)
{
    int_vect.push_back(input);
    cout << "> ";
}

现在您不再导致错误,cin因为一切都是整数,您的第二个输入现在可以工作。

要获得正确的修复,您需要查看我在评论中提出的建议。基本上,当您尝试读取整数和/或字母时,您需要先读取字符串,然后再转换为整数。

于 2013-04-03T07:37:32.553 回答