如何从用户那里获得输入字符串而不是示例,然后计算空格、标点符号、数字和字母.C++



这是我的代码。用户将给出一个输入(任何字符串),而不是"这是一个测试。1 2 3 4 5"。

然后,它将显示空格、标点符号、数字和字母的数量作为输出字符串。

#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;
}

您希望将std::getlinestd::cin结合使用,后者从标准C输入流stdin 中读取

  • std::getline从输入流中读取字符并将其放入字符串中
  • std::cin是与stdin相关联的输入流

通常,您希望向用户输出提示:

std::cout << "Please enter your test input:n";

然后,您想要创建一个std::string,并将std::getlinestd::cin一起用于将用户的输入存储到该字符串中:

std::string input;
std::getline(std::cin, input);

此时,您的程序将被阻止,直到用户输入并按enter键。

一旦用户按下回车键,std::getline将返回,您可以对字符串的内容执行任何操作

示例:

#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;
}

输出:

$ ./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

最新更新