احصل على قائمة بالأرقام من Stdin وتكزفها
-
16-09-2019 - |
سؤال
كيف يمكنني الحصول على قائمة بالأرقام من المستخدم ثم قم بتكوينها.
هذا هو ما لدي لكنه لا يحصل على أي شيء ما عدا الرقم الأول:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line = "";
cin >> line;
stringstream lineStream(line);
int i;
vector<int> values;
while (lineStream >> i)
values.push_back(i);
for(int i=0; i<values.size(); i++)
cout << values[i] << endl;
system("PAUSE");
return 0;
}
المنشورات ذات الصلة:
C ++، الذهاب من سلسلة إلى stringstream لتتجه
المميز الدولي
المحلول
أعتقد أن CIN >> يكسر في Whitespace، مما يعني أنك تحصل على الرقم الأول الذي تم إدخاله فقط.
يحاول:
getline(cin, line);
نصائح أخرى
ربما تكون هذه أسهل طريقة لقراءة القيم cin
في حاوية:
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> values;
std::copy(
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(values));
// For symmetry with the question copy back to std::cout
std::copy(
values.begin(),
values.end(),
std::ostream_iterator<int>(std::cout,"\n"));
}
مثل Donnie ذكر CIN فواصل بيضاء، لذلك التغلب على هذا يمكننا استخدام "getline ()"، والأثناء التالي يعمل بشكل جيد:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line = "";
::getline(std::cin,line,'\n');
std::stringstream lineStream(line);
int i;
std::vector<int> values;
while (lineStream >> i)
values.push_back(i);
for(int i=0; i<values.size(); i++)
cout << values[i] << endl;
system("PAUSE");
return 0;
}
على رأس الرئيسي
string line = "";
getline (cin, line );
stringstream lineStream(line);
نعم، وهي نسخة سلسلة من getline، لا يوجد istream واحد.
حسنا: بافيل مينوف لديه أفضل إجابة.
ولكن كل الناس يذكرون أن سين يكسر في الفضاء الأبيض.
هذا شيء جيد (لأنه يتجاهل أيضا مساحة بيضاء)؛
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int i;
vector<int> values;
// prefer to use std::copy() but this works.
while (std::cin >> i)
{
values.push_back(i);
}
// prefer to use std::copy but this works.
for(vector<int>::const_iterator loop = values.begin();loop != values.end();++loop)
{
cout << *loop << endl;
}
return 0;
}
لا تنتمي إلى StackOverflow