gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:58:19 31 4
gpt4 key购买 nike

这是我的代码。用户将提供输入(任何字符串)而不是“这是一个测试。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::getline连同std::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);

此时您的程序将阻塞,直到用户键入他们的输入并按下回车键。

一旦用户按下回车键,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

关于c++ - 我如何从用户而不是示例中获取输入字符串,然后计算空格、标点符号、数字和字母。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693038/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com