How to Input a String in C++
In this tutorial, we are going to discuss the topic of how to input a string in C++, so we start with what a string is and its declaration as well as different kinds of assigning values to the arrays, Functions used to input a string in C++ with examples, and a clear explanation of those example programs.
String Data Structure
A collection of characters or an array makes up the string data structure. We can construct the character arrays to utilize a string data structure or use the built-in string class in C++.
We can create a string by defining an array with one dimension of characters. A string's termination with the null character 0 is the only distinction between it and a character array.
The string can be declared in the same manner as arrays, with the difference that the data type of the string's members will always be char:
char My_String_Array[3];
The array's name, My_String_Array, and its data types, char and string, are used here.
Functions to input a String in C++
We'll now look at how to input a string in C++. Taking input of strings refers to taking a string from user input. Various ways exist to collect user input depending on a string's shape. The string might contain a single word, like "Hey," or multiple words, like "How have you been?"
In this tutorial, we'll carefully look at four approaches to entering a string corresponding to the requirements or types of text that must be allowed as input.
Different kind of ways for Assigning values to the array are:
String_array[0] = 'A';
String_array[1] = 'r';
String_array[2] = 'm';
String_array[3] = 'y’:
(or)
char String_array[5] = {'A', 'r', 'm', 'y', '\0'};
(or)
char String_array[] = {'A', 'r', 'm', 'y', '\0'};
(or)
char String_array[5] = "Army";
(or)
char String_array[] = "Army";
These are the various ways of assigning values to the array. Hope you got a good idea of assigning the values to the array in string.
cin() Function:
In C++, we typically combine the cin keyword with the extraction operator (>>) to deliver input from the user to our program. Through our program's cin() function, the iostream header file is imported.
The "in" in "cin" stands for "input," while the "c" stands for "character." Therefore, the term "character input" is "cin."
The extraction operator >> is used in conjunction with the cin object
to receive a stream of characters.
The extraction operator sees an empty line, a tab, or a newline as the terminating character by default. As a result, if the user entered the string "Hi" as the input, the cin() method would accept it as such; however, let's say the user entered "I am the Cutie" instead. Then, in such a scenario, only the first word, "I," will be taken into account as the input, and the string "am the Cutie" will be thrown away because the cin() method will treat the space after "I" as the concluding character.
Therefore, the cin() method will begin reading when the first non-whitespace character appears and stop reading when the next one does while accepting input.
Syntax:
cin >> string_name;
In this case, the cin keyword can be written using the extraction operator (>>), followed by the string's name, which will be used as user input.
Example:
Code:
#include <iostream>
using namespace std;
int main() {
char string[6]; // Declare a character array to store the input string, which can hold up to 5 characters plus the null terminator '\0'.
cout << "Enter the string/character array:";
cin >> string; // Use cin to read and store a string in the 'string' array.
cout << "Entered Character array is" << endl;
cout << string << endl; // Display the entered string.
return 0; // Exit the program.
}
Explanation:
- To make accessing the standard C++ library components easier, include the header for input and output operations and use namespace std.
- To save the input string, you declare a char string character array [6]. This array contains 5 characters plus a '0' null terminator to indicate the end of the string.
- You use cout to display a prompt message asking the user to enter a few characters.
- To read a string from the standard input (keyboard) and save it in the str character array, use the command cin >> string. If the user enters a string containing spaces, just the characters until the first space will be kept in the string since it reads characters until a whitespace (space, tab, or newline) is encountered.
- Using cout, you can see the entered string. The only characters displayed are those in the string up to the null terminator '0'.
- The program then returns 0 to denote a successful execution.
- Remember that it can hold upto 5 characters only.
Output:
![How to Input a String in C++](https://static.tutorialandexample.com/cpp/how-to-input-a-string-in-cpp1.png)
getline() function:
We frequently use the getline() function to read a line of text or a sentence to get around the restriction we examined earlier with the cin() technique.The string variable and cin are its first and second parameters, respectively.
A header file contains a built-in, predefined function called getline(). It will accept a sentence from the input stream if the delimiting character cannot be located.
Two approaches can be used to apply the getline() method. The input string and cin are the only two parameters to be given.Three variables can be supplied as an alternative. The first two parameters are the same as before, and the third is the delimiter character we want to utilize as an ending character.
Syntax:
getline(cin, string_name, delimiterCharacter);
string_name here refers to the string variable's name, while delimeterCharacter designates the final character.
Example:
Code:
#include <iostream>
#include <string>
int main() {
std::string inputString; // Declare a string variable to store the user's input.
std::cout << "Please enter a string: "; // Display a message asking the user to enter a string.
std::getline(std::cin, inputString);
// std::getline reads an entire line, including spaces, until the user presses the Enter key.
std::cout << "You have entered the string: " << inputString << std::endl; // Display the entered string.
return 0; // Exit the program with a status code 0 to indicate successful execution.
}
Explanation:
- The string> header is needed for handling strings, while the iostream> header is needed for input and output operations.
- Inside the main() function, an inputString std::string variable can store user input. Since std::string can dynamically modify its size to fit the user's input, buffering problems are not a concern like character arrays.
- A prompt message requesting a string from the user is displayed using std::cout. On the console, this message appears.
- A line of text is read from the keyboard's standard input using the std::getline(std::cin, inputString) function, and it is then saved in the inputString variable. Unlike cin >> str; std::getline reads a full line, including spaces, until the user clicks the Enter key. InputString is used to hold the text that was entered.
- The entered string is shown on the terminal along with the words "You have entered string:" by using std::cout once again. User input is displayed in this.
- Finally, it returns 0 with the syntax return 0 to show that the program has successfully run. When the application is finished, the operating system receives this status code. An error-free application is often indicated with a status code of 0.
Output:
![How to Input a String in C++](https://static.tutorialandexample.com/cpp/how-to-input-a-string-in-cpp2.png)
gets() Function:
When using the gets() method in C, characters are read until a new line begins or you press the enter or return key. This can be used when receiving user input as a string containing numerous words. Using the gets() function, an entire sentence can be recorded. It is used to get over the drawback of the cin() function. As a result, the gets() method allows the user to enter strings separated by spaces.
- getline() is a C++ function, whereas gets() is a C function. This is the difference between the two functions. C++ and C can use the gets() method because they support all C functions.
- getline() pulls data in a prepared line-by-line format, whereas gets() takes data from a stream character by character and returns its value. This is another difference between how gets() and getline() operate.
Syntax:
gets(string_name);
Here, string_name refers to the name of the input of the string.
Example:
Code:
#include<stdio.h>
int main() {
// Declare String Variable
char string[20];
printf("Enter your name:\n");
gets(string);
// The input will be stored in the string variable
printf("The entered name(string) is:\n");;
printf("%s", string);
}
Explanation:
- For common input and output operations like printf and gets, we use the stdio.h> header file.
- The string variable is declared a character array (string) with a 20-character limit. The input from the user is kept in this array.
- The application displays a prompt message requesting the user's name using printf. For better formatting, newlines are created with the n character.
- To read a line of text from the keyboard's standard input and add it to the string array, the gets() function is used. As a result of its lack of bounds checking and risk to buffer overflows, gets() is regarded as dangerous and no longer available in current C programming.
- After reading the name, the application prints a message indicating it will display the entered name (string).
- The name (string) entered is printed using printf and the%s format specifier.
Output:
![How to Input a String in C++](https://static.tutorialandexample.com/cpp/how-to-input-a-string-in-cpp3.png)
stringstream() Function:
With the help of the stringstream() function, you can read from a string like a stream by connecting it to a stream object. The primary purpose of this function is to "split" a string into different words while treating the input string like a stream.
We use the sstream header for accessing stringstream.
Syntax:
stringstream stringstream_object_name(string_name);
StringStream_Object_name in the above syntax stands for the name of the stringstream object that will break and save the original string (string_name) to words.
Example:
Code:
#include <iostream>
#include <string>
#include <sstream>
int main() {
// Declare variables
std::string inputString;
std::string word;
// Ask the user to enter a string
std::cout << "Enter a string/sentence: ";
std::getline(std::cin, inputString);
// Create a stringstream object
std::stringstream ss(inputString);
// show words from the input/entered string
std::cout << "Words in the entered string:" << std::endl;
while (ss >> word) {
std::cout << word << std::endl;
}
return 0;
}
Explanation:
- The required header files, iostream for input and output, a string for handling strings, and sstream for stringstream, are included.
- We declare words to temporarily store certain words from the input string and inputString to save the user's input as a whole.
- To request a string from the user, we utilize std::cout.
- A std::stringstream object named ss is created once the user enters a string and is initialized with the input string.
- Once more, we display a message informing the user that the words in the given string will be displayed using std::cout.
- To extract and show certain words from the stringstream inside a while loop, use the ss >> word command. The loop is repeated until there are no more words in the stringstream.
Output:
![How to Input a String in C++](https://static.tutorialandexample.com/cpp/how-to-input-a-string-in-cpp4.png)
Conclusion:
In this tutorial, we have seen how to input a string in different methods such as cin(), getline(), gets(), and stringstream(). In the cin() function, we can input only a single word, whereas the getline() function takes the entire sentence until the delimiter character is not found. However, the gets() function reads the characters until we press the enter or return key(But remember, mostly don't use this method since its lack of bounds checking and risk to buffer overflows; gets() is regarded as dangerous and no longer available in current C programming) and finally stringstream() function is used to "split" a string into different words while treating the input string like a stream.