This C++ program illustrates the use of command line arguments. The parameter argc passed to the main of the C++ program contains the number of arguments passed to the main function and the argv parameter contains the pointers to the character strings passed as the command-line arguments. Based on the value of these arguments, the case of the string entered can be changed accordingly.
Here is the source code of the C++ program illustrates the use of command line arguments. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Illustrate Command Line Arguments
*/
#include <iostream>
#include <cctype>
#include <string>
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cout << "Command-line Argument missing " << std::endl;
return 0;
}
else if (argc == 2)
{
if (strcmp(argv[1], "toupper") == 0)
{
std::string str;
std::cout << "Enter the string ";
std::cin >> str;
for (int i= 0; i < str.length(); i++)
{
str[i] = toupper(str[i]);
}
std::cout << "The string is now " << str
<< std::endl;
}
else if (strcmp(argv[1], "tolower") == 0)
{
std::string str;
std::cout << "Enter the string ";
std::cin >> str;
for (int i= 0; i < str.length(); i++)
str[i] = tolower(str[i]);
std::cout << "The string is now " << str
<< std::endl;
}
else
std::cout << "Unmatched second command-line argument"
<< std::endl;
}
return 0;
}
$ a.out toupper Enter the string programming The string is now PROGRAMMING $ ./a.out tolower Enter the string PROGRAMMING The string is now programming $ ./a.out Command-line Argument missing
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice Programming MCQs
- Buy Computer Science Books
- Apply for C++ Internship
- Practice Computer Science MCQs
- Apply for Computer Science Internship