Precautions in online OJ

Keywords: C++ Programming

When using OJ online for the first time, the topic is as follows:

Enter a string to find the set of characters it contains
Enter a description:
Enter a string for each group of data. The maximum length of the string is 100, and it only contains letters. It cannot be an empty string. It is case sensitive.
Output Description:
One line for each group of data, output the character set according to the original character sequence of the string, that is, the letters that appear repeatedly and come back do not output.

This is the first code submitted:

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<string>
#include<stdlib.h>

int main()
{
    string s1;
    s1.reserve(100);
    string s2;
    int i = 0;
    s2.reserve(100);
    while(cin>>s1)
    {
        for (i = 0; i < s1.size(); i++)
    {
        if (s2.find(s1[i]) == -1)
        {
            s2.push_back(s1[i]);
        }
    }
    auto it = s2.begin();
    while (it != s2.end())
    {
        cout << *it;
        it++;
    }
    }

    system("pause");
    return 0;
}

Such code can be completed logically without any errors, but fails to pass the test case.
Through repeated pondering and research, it turns out that there is no newline in the output and the contents in s1 and s2 are not cleared after each cycle of input string, so the output will be repeated in the next cycle.
The correct code is as follows.

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<string>
#include<stdlib.h>

int main()
{
    string s1;
    s1.reserve(100);
    string s2;
    int i = 0;
    s2.reserve(100);
    while(cin>>s1)
    {
        for (i = 0; i < s1.size(); i++)
    {
        if (s2.find(s1[i]) == -1)
        {
            s2.push_back(s1[i]);
        }
    }
    auto it = s2.begin();
    while (it != s2.end())
    {
        cout << *it;
        it++;
    }
        cout<<endl;
        s1.clear();
        s2.clear();
    }

    system("pause");
    return 0;
}

So here are some summary of programming in online OJ:
On line OJ needs to input through cyclic input (while)
Note the output format: it is necessary to add endl after the output of each cycle;
Note that the state of each variable or container is updated to the initial state at the end of each cycle.

Posted by awais_ciit on Wed, 30 Oct 2019 21:06:37 -0700