如何从控制台读取整数到与cin向量
我想从控制台读取整数到我的整数向量。我希望从单行读取整数直到用户点击输入。我一直在尝试使用getline和stringstream,但在按下Enter键后,它一直在寻找输入。任何解决方案如何从控制台读取整数到与cin向量
高级描述:该程序从控制台读入数字,并将它们推到矢量的后面。然后对矢量进行排序,并创建两个指针指向前后。然后用户可以输入一个总和,程序将通过取两个指针的总和以线性时间进行搜索。然后指针将继续向一个方向移动,直到他们找到这样的总数或确定不存在这样的总和。
#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();
}
cin
与输入操作>>
吃所有的空格它到达你面前,所以input
永远不会\n
。
但这甚至不是最大的问题。 cin >> input
不会返回刚刚读取的内容,而是返回流本身的引用(请参阅here)。这意味着你的代码while (cin >> input != "\n")
没有完全符合你的想法(老实说,甚至不应该编译)。
读取一行从标准输入整数为载体,你会因此像这样:
string line;
int num;
vector<int> v;
getline(cin, line);
istringstream iss(line);
while(istringstream >> num) {
v.push_back(num);
}
使用
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
}
// }
你可以通过'std :: istream_iterator'和'std :: back_inserter'使用std :: copy()来摆脱'while'循环,例如:'std :: copy(std :: istream_iterator
虽然(得到它?)这是令人印象深刻的STL使用,但我不得不说更难以理解有经验的程序员。有时这些实用程序会导致更短,更易读的代码,有时它们不会。 – jwilson
给出以下答案的选项2甘德。唯一的区别是你使用的是cin而不是文件:https://stackoverflow.com/a/7868998/4581301 – user4581301
代码中的getline和stringstream是哪里? – Barmar
'getline'和'stringstream'是解决这个问题的正确方法,所以你一定是做错了。 'getline'不应该在循环中 - 你只做一次,然后从循环中的'stringstream'中读取。 – Barmar