ASCII строка, объединенная - PullRequest
0 голосов
/ 28 марта 2019

Я работаю над программой, которая объединяет две строки в алфавитном порядке ASCII, а также удаляет все повторяющиеся буквы. Пока у меня есть

#include <iostream>
using namespace std;

int main() {
string s1, s2;
string combined;
while (true) {
    cin >> s1 >> s2;
    if (s1 == "quit" && s2 == "quit") break;
    cout << "Read " << "\"" << s1 << "\"" << " and " << "\"" << s2 << "\" -> ";
    combined = s1+s2;
    cout << combined << endl;
}
cout << "Bye";
return 0;
}

вывод должен выглядеть как Read "binarytriangle" and "ANSIStandard" -> "AINSabdegilnrty", но я не могу понять, как на самом деле объединить их на основе порядка алфавита и удалить повторяющиеся буквы. В Интернете я только нашел, как получить числовое значение char на основе порядка ASCII, а не порядка двух строк. Я думаю об использовании цикла for, но я не уверен, что я должен поместить в круглые скобки.

1 Ответ

0 голосов
/ 28 марта 2019

Это относится к тому, что @molbdnilo написал в комментарии, но со встроенными комментариями в коде.Эта часть:

while (true) {
    cin >> s1 >> s2;

является потенциальной ловушкой.Если сторона записи закрывает поток, вы получите бесконечный цикл.Кроме того, использование пространства имен std; - плохая практика.

#include <iostream>
#include <algorithm> // std::sort

// Dont do this:
// using namespace std;

int main() {
    std::string s1, s2;
    std::string combined;

    // check if  std::cin  is true in a boolean context after having tried to extract
    // the strings. If it's not true, you'll may end up with an endless loop (if
    // the writing side closed the stream).
    while(std::cin >> s1 >> s2) {
        if(s1 == "quit" && s2 == "quit") break;
        std::cout << "Read "
                  << "\"" << s1 << "\""
                  << " and "
                  << "\"" << s2 << "\" -> ";
        combined = s1 + s2;

        // sort the chars in the string.
        std::sort(combined.begin(), combined.end());

        // move repeated chars to the end of the string and return an iterator to
        // what will become the new end of the string
        std::string::iterator new_end = std::unique(combined.begin(), combined.end());
        // the string is just as long as before here, but all the repeated chars
        // are at the end, so,

        // erase all chars from new_end to current end()
        combined.erase(new_end, combined.end());

        std::cout << combined << "\n"; // std::endl for flushing is unncessary in most cases
    }
    std::cout << "Bye\n";
}
...