繁体   English   中英

如何从用户而不是示例中获取输入字符串,然后计算空格,标点符号,数字和字母。 C ++

[英]How do I take Input string from user instead of the example and then Count spaces, punctuation, digits, and letters. 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。

用户按下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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM