C++ 如何从用户而不是示例中获取输入字符串,然后计算空格、标点符号、数字和字母。C++;
这是我的密码。 用户将给出一个输入(任何字符串),而不是“这是一个测试。1 2 3 4 5” 然后,它将显示空格数、标点符号、数字和字母作为输出字符串C++ 如何从用户而不是示例中获取输入字符串,然后计算空格、标点符号、数字和字母。C++;,c++,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,
#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;
int main(){
const char*str=“这是一个测试。1 2 3 4 5”;
整数字母=0,空格=0,点号=0,数字=0;
cout您想与从标准C输入流读取的数据一起使用吗
std::getline
从输入流中读取字符并将其放入字符串中
std::cin
是与stdin
通常,您希望向用户输出提示:
std::cout << "Please enter your test input:\n";
此时,您的程序将阻塞,直到用户输入并按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
问题是什么,或者您认为您的代码有什么问题?@SteveLorimer无法正常工作。OP应该使用std::getline()
取而代之。@user0042 my bad,你是对的-你需要结合使用std::getline
和std::cin
-回答updated@MoshiurRahman如果这个答案对你有帮助,请花点时间接受它(点击问题左边的勾号)
$ ./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