[英]How do I take Input string from user instead of the example and then Count spaces, punctuation, digits, and letters. C++
This is my code. 这是我的代码。 User will give an input(any string) instead of the "This is a test. 1 2 3 4 5".
用户将提供一个输入(任何字符串),而不是“这是一个测试。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
和std::cin
从标准C输入流stdin中读取
std::getline
reads characters from an input stream and places them into a string std::getline
从输入流中读取字符并将其放入字符串中 std::cin
is the input stream associated with stdin
std::cin
是与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
,并使用std::getline
和std::cin
将用户输入的内容存储到该字符串中:
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. 此时,您的程序将被阻止,直到用户键入他们的输入,然后按Enter。
Once the user presses enter, std::getline
will return, and you can do whatever you want with the contents of the string 用户按下Enter键后,
std::getline
将返回,并且您可以对字符串的内容进行任何操作
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.