This is my code. User will give an input(any string) instead of the "This is a test. 1 2 3 4 5".
Then it will show number of spaces, punctuation, digits, and letters as output string.
#include <iostream>
#include <cctype>
using namespace std;
int main() {
const char *str = "This is a test. 1 2 3 4 5";
int letters = 0, spaces = 0, punct = 0, digits = 0;
cout << str << endl;
while(*str) {
if(isalpha(*str))
++letters;
else if(isspace(*str))
++spaces;
else if(ispunct(*str))
++punct;
else if(isdigit(*str))
++digits;
++str;
}
cout << "Letters: " << letters << endl;
cout << "Digits: " << digits << endl;
cout << "Spaces: " << spaces << endl;
cout << "Punctuation: " << punct << endl;
return 0;
}
You want to use std::getline
in conjunction with std::cin
which reads from the standard C input stream stdin
std::getline
reads characters from an input stream and places them into a string std::cin
is the input stream associated with stdin
Typically you want to output a prompt to the user:
std::cout << "Please enter your test input:\n";
Then you want to create a std::string
, and use std::getline
with std::cin
to store the user's input into that string:
std::string input;
std::getline(std::cin, input);
At this point your program will block until the user types in their input, and presses enter.
Once the user presses enter, std::getline
will return, and you can do whatever you want with the contents of the string
Example:
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
std::cout << "Enter the test input:\n";
std::string input;
std::getline(std::cin, input);
const char *str = input.c_str();
int letters = 0, spaces = 0, punct = 0, digits = 0;
cout << str << endl;
while(*str) {
if(isalpha(*str))
++letters;
else if(isspace(*str))
++spaces;
else if(ispunct(*str))
++punct;
else if(isdigit(*str))
++digits;
++str;
}
cout << "Letters: " << letters << endl;
cout << "Digits: " << digits << endl;
cout << "Spaces: " << spaces << endl;
cout << "Punctuation: " << punct << endl;
return 0;
}
Output:
$ ./a.out
Enter the test input:
This is a test 1 2 3 4
This is a test 1 2 3 4
Letters: 11
Digits: 4
Spaces: 7
Punctuation: 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.