如何使用cin

时间:2017-08-03 18:26:24

标签: c++ vector sstream

我正在尝试从控制台读取整数到我的向量向量中。我想继续从一行读取整数,直到用户点击回车。我一直在尝试使用getline和stringstream,但是在按下回车后它一直在寻找输入。有解决方案吗

高级描述:该程序从控制台读取数字并将它们推送到向量的背面。然后对矢量进行排序,并创建两个指针指向后面和前面。然后,用户可以输入一个总和,然后程序将通过取两个指针的总和在线性时间内搜索。然后指针将继续沿一个方向移动,直到它们找到这样的总和或确定不存在这样的总和。

#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;

int findSum(vector<int> tempVec, int sum)
{
    int i;
    cout << "Sorted sequence is:";
    for ( i = 0; i < tempVec.size(); i++ )
        cout << " " << tempVec[i];
    cout << endl;

    int *ptr1 = &tempVec[0];
    cout << "ptr1 points to: " << *ptr1 << endl;
    int *ptr2 = &tempVec[tempVec.size() - 1];
    cout << "ptr2 points to: " << *ptr2 << endl;

    int count = 0;
    while ( ptr1 != ptr2 )
    {

        if ( (*(ptr1) + *(ptr2)) == sum )
        {
            cout << *(ptr1) << " + " << *(ptr2) << " = " << sum;
            cout << "!" << endl;
            return count;
        }
        if ( (*(ptr1) + *(ptr2)) < sum)
        {
            cout << *(ptr1) << " + " << *(ptr2) << " != " << sum;
            ptr1 = ptr1 + 1;
            cout << ". ptr1 moved to: " << *ptr1 << endl;
            count++;
        }
        else 
        {
            cout << *(ptr1) << " + " << *(ptr2) << " != " << sum;
            ptr2 = ptr2 - 1;
            cout << ". ptr2 moved to: " << *ptr2 << endl;
            count++;
        }
    }
    return -1;
}

int main()
{
    int ValSum;
    cout << "Choose a sum to search for: ";
    cin >> ValSum;


    vector<int> sumVector;
    int input;
    cout << "Choose a sequence to search from: ";
    while ( cin >> input != "\n" )
    {
        //getline(cin, input);
        if ( cin == '\0' )
            break;
        sumVector.push_back(input);
    }
    sort(sumVector.begin(), sumVector.end());


    int count = findSum(sumVector,ValSum);
    if ( count == -1 )
        cout << "\nThe sum " << ValSum << " was NOT found!" << endl;
    else 
    {
        cout << "\nThe sum " << ValSum << " was found!" << endl;
        cout << count + 1 << " comparisons were made." << endl;
    }
    sumVector.clear();
} 

2 个答案:

答案 0 :(得分:1)

带有输入操作符cin

>>在它到达之前会占用所有空格,因此input永远不会是\n

但这甚至不是最大的问题。 cin >> input不返回刚刚读取的内容,而是返回对流本身的引用(请参阅here)。这意味着你的代码while ( cin >> input != "\n" )没有做到你想的那么多(老实说,甚至不应该编译)。

要从stdin读取一行整数到向量中,你会这样:

string line;
int num;
vector<int> v;

getline(cin, line);
istringstream iss(line);

while(istringstream >> num) {
    v.push_back(num);
}

答案 1 :(得分:0)

使用

std::vector<int> v;
std::string line;

// while (!v.empty()) { // optional check to make sure we have some input
std::getline(std::cin, line); // gets numbers until enter is pressed
std::stringstream sstream(line); // puts input into a stringstream
int i;

while (sstream >> i) { // uses the stringstream to turn formatted input into integers, returns false when done
    v.push_back(i); // fills vector
}
// }