问题
I got this simple program read in a string like "13 11 9 10". I wanna split string then sort them. however the sort() seems not working, any help? input: 13 11 9 10 , output: 13 11 9 10 Thanks!
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> split(string s)
{
istringstream iss(s);
vector<int> result;
do{
string sub;
iss>>sub;
if(sub!="")
result.push_back((int)atoi(sub.c_str()));
}while(iss);
return result;
}
int main(void)
{
string s;
while(cin>>s)
{
vector<int> vec;
vec=split(s);
sort(vec.begin(), vec.end());
for (int i = 0; i < vec.size(); ++i)
{
cout<<vec[i]<<endl;
}
}
}
回答1:
That's because cin >> s
stops at the first whitespace.
In other words, if you type 1 4 2 3
, s
contains 1
only, and not the entire line.
Instead, use the following to read the entire line:
std::getline(std::cin, s);
回答2:
your main section of code is incorrect, cin already splits data into parts, use cin.getline with buffer or what Cicida suggests above, my working code looks like this:
string s;
char buffer[ 256 ];
do
{
cin.getline( buffer, 255 );
s.assign( buffer );
vector<int> vec;
vec=split(s);
sort(vec.begin(), vec.end());
for (int i = 0; i < vec.size(); ++i)
{
cout<<vec[i]<<endl;
}
}while( !s.empty( ));
来源:https://stackoverflow.com/questions/11535854/why-is-the-sort-not-working