C++ program to get input from user
When writing a program in any programming language, receiving input is the basic job we do in almost all programs. Sometimes we get input directly from the console and sometimes we get input from a file. Getting input from a file has certain benefits as it does not require us to type it over and over again and sometimes we can save some good input test cases to a file. However, in this article we will focus on console-based input. We will learn different techniques for getting input from the user in C.
There are several different ways to get input from the console. Some of them are C-like methods, while others use input streams that exist in C. We will cover them one by one and provide some examples for better understanding.
Use the scanf() function to receive input
In C language, we use the scanf() function to scan input from the console in the form of a formatted string. This function is also available in C, so to receive input in a formatted form, use the scanf() method.
grammar
Basic syntax of the scanf() method, including format string.
scanf ( “<format string>”, <address of variable> );
scanf() formatted format specifier.
Format specifier | The Chinese translation ofDescription | is:Description |
---|---|---|
%c | For single character input | |
%s | For strings without spaces | |
%Hi | Short signed integer | |
%hu | Short unsigned integer | |
%Lf | 长双 | |
%d | Decimal integer (signed), assuming base 10 | |
%i | Integer (automatically detect base) | |
%o | Octal integer | |
%x | Hexadecimal integer | |
%p | pointer | |
%f | Floating point number |
Example 1
is:Example 1
#include <iostream> using namespace std; void takeInput() { int x; char s[50]; // C like string or character array char c; float f; cout << "Enter an integer: "; scanf( "%d", &x ); cout << "\nYou have entered an integer: " << x << endl; cout << "Enter a character: "; scanf( " %c", &c ); cout << "\nYou have entered a character: " << c << endl; cout << "Enter a float value: "; scanf( "%f", &f ); cout << "\nYou have entered float value: " << f << endl; cout << "Enter a string: "; scanf( "%s", s ); //string do not need address //convert to C++ like string from C like string string SCpp; SCpp.assign(s); cout << "\nYou have entered the string: " << SCpp << endl; } int main(){ takeInput(); }
Output
Enter an integer: 5 You have entered an integer: 5 Enter a character: K You have entered a character: K Enter a float value: 2.56 You have entered float value: 2.56 Enter a string: HelloWorld You have entered the string: HelloWorld
In this method, it works for other data types, but for strings, it only accepts C-like strings or character arrays. To display a string using "cout" we need to convert it to a C-like string object. Otherwise, we can use printf() function to display the output. These are basic examples. Now let's see the effect of formatting the string in the next example.
Example 2
is translated as:Example 2
#include <iostream> using namespace std; void takeInput() { int dd, mm, yyyy; cout << "Enter a date in dd-mm-yyyy format: "; scanf( "%d-%d-%d", &dd, &mm, &yyyy ); cout << "\nThe given date is: "; printf( "%d/%d/%d", dd, mm, yyyy ); } int main(){ takeInput(); }
Output
Enter a date in dd-mm-yyyy format: 14-10-2022 The given date is: 14/10/2022
In this example, we receive input in the form (dd-mm-yyyy), it will not accept any other format for these three integer values. And in our output, we display the same date in another format (dd/mm/yyyy). This is what formatted string input is actually for. Next, we'll see a simpler form using the "cin" input stream to directly input any type of data into a specified variable.
Use cin to receive input in C
cin is a C input stream class that uses the extraction operator>> to obtain input from the stream. This operator automatically inserts a value into the specified variable by getting input from the console. The syntax is as follows.
grammar
Basic syntax of cin method
cin >> <input variable name>
Example 1
is:Example 1
#include <iostream> using namespace std; void takeInput() { int x; string s; char c; float f; cout << "Enter an integer: "; cin >> x; cout << "\nYou have entered an integer: " << x << endl; cout << "Enter a character: "; cin >> c; cout << "\nYou have entered a character: " << c << endl; cout << "Enter a float value: "; cin >> f; cout << "\nYou have entered float value: " << f << endl; cout << "Enter a string: "; cin >> s; cout << "\nYou have entered the string: " << s << endl; } int main(){ takeInput(); }
Output
Enter an integer: 8 You have entered an integer: 8 Enter a character: L You have entered a character: L Enter a float value: 3.14159 You have entered float value: 3.14159 Enter a string: WeAreLearningC++InputTaking You have entered the string: WeAreLearningC++InputTaking
Like other variables, we can use strings directly instead of making them as character arrays. In this method, it automatically assigns the given input to a string object. However, there is a problem with strings. We cannot enter multi-word strings this way. If we write a multi-word string, it will only take the first word. Let us see this in the example below.
Example 2
is translated as:Example 2
#include <iostream> using namespace std; void takeInput() { string s; cout << "Enter a string: "; cin >> s; cout << "\nYou have entered the string: " << s << endl; } int main(){ takeInput(); }
Output
Enter a string: Hello World, This is a nice day You have entered the string: Hello
To overcome this problem, we need to use the getline() function to get a space-delimited string. In this method it ends reading the text when a newline character is encountered.
grammar
getline(std::cin, <string variable>)
Example 3
is:Example 3
#include <iostream> using namespace std; void takeInput() { string s; cout << "Enter a string: "; getline(cin, s); cout << "\nYou have entered the string: " << s << endl; } int main(){ takeInput(); }
Output
Enter a string: Hello World, Have a nice day You have entered the string: Hello World, Have a nice day
in conclusion
In this article, we have seen different usages of reading user input using the scanf() method and the cin stream. Assigning inputs to other variable types is straightforward. However, neither the %s format specifier nor the cin class accept input strings with spaces. Like the C language, there is a designated function in C for reading a string with space-separated words. You can use the getline() method to accept this input string. We can also get input from files and string streams.
The above is the detailed content of C++ program to get input from user. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

The application of static analysis in C mainly includes discovering memory management problems, checking code logic errors, and improving code security. 1) Static analysis can identify problems such as memory leaks, double releases, and uninitialized pointers. 2) It can detect unused variables, dead code and logical contradictions. 3) Static analysis tools such as Coverity can detect buffer overflow, integer overflow and unsafe API calls to improve code security.

C still has important relevance in modern programming. 1) High performance and direct hardware operation capabilities make it the first choice in the fields of game development, embedded systems and high-performance computing. 2) Rich programming paradigms and modern features such as smart pointers and template programming enhance its flexibility and efficiency. Although the learning curve is steep, its powerful capabilities make it still important in today's programming ecosystem.

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

The future of C will focus on parallel computing, security, modularization and AI/machine learning: 1) Parallel computing will be enhanced through features such as coroutines; 2) Security will be improved through stricter type checking and memory management mechanisms; 3) Modulation will simplify code organization and compilation; 4) AI and machine learning will prompt C to adapt to new needs, such as numerical computing and GPU programming support.

C isnotdying;it'sevolving.1)C remainsrelevantduetoitsversatilityandefficiencyinperformance-criticalapplications.2)Thelanguageiscontinuouslyupdated,withC 20introducingfeatureslikemodulesandcoroutinestoimproveusabilityandperformance.3)Despitechallen
