why is the sort() not working?

帅比萌擦擦* 提交于 2019-12-11 01:57:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!