How to add auto-completion to your C++ console application

Evans Ehiorobo
How-Tos
Published in
3 min readOct 16, 2019

Auto-completion is a useful tool, no doubt. Many times when searching for something on Google, I write out the first few characters and let it complete the word (and sometimes sentence) for me.

In this article, I will describe how to add auto-completion to your C++ application.

Let’s suppose you have an application where you want the user to enter some text and the text the user will type in is almost always going to be part of a set of words or sentences, you can assist the user by adding auto-completion so that they simply have to type in the first few characters of the text and your application will complete it for them.

We will call this set of words or sentences the dictionary for the user input. In this article, our dictionary will consist of four tech companies whose names begin with the letter “a”:

string DICTIONARY[] = {
"alibaba",
"alphabet",
"amazon",
"apple"
};

We begin by collecting the user’s input and storing it in a variable:

int main(int argc, char** argv) {
string input;

cin >> input;

return 0;
}

Next, we find out whether the text the user entered is contained in the dictionary. To do that, we will loop through the items in the dictionary and for each one, check if it contains the text the user entered:

string getMatch(string text) {
// returns the closest match in the DICTIONARY to text

for (int i = 0; i < 4; i++) {
if (contains(DICTIONARY[i], text)) {
return DICTIONARY[i];
}
}

return text;
}

The function getMatch() checks through the dictionary for the closest matching item and returns it. If no item matches the input text, then the text is returned.

In order for us to check whether a string contains another string, we use the contains() function:

bool contains(string str1, string str2) {
// returns true if str1 contains str2, else false

return (str1.find(str2) != string::npos);
}

Where npos means “until the end of the string”, that is, if str2 has no index in str1 until the end of str1 is reached, then return false.

We can now get this closest match in the main() function and print it in the console:

int main(int argc, char** argv) {
string input, closestMatch;

cin >> input;

closestMatch = getMatch(input);
cout << closestMatch;

return 0;
}

Here are some results of the application being tested:

Testing with input “ali” gives “alibaba”
Testing with input “am” gives “amazon”
Testing with input “faceb” gives “faceb”

As we can see, the application correctly completes the user’s input as long as it has a match in the dictionary. If there is no match, the input is left untouched.

Thanks for following this far. The full code for this project can be found here. If you have any comments or questions, please drop them below.

--

--