[英]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::getline
和std::cin
從標准C輸入流stdin中讀取
std::getline
從輸入流中讀取字符並將其放入字符串中 std::cin
是與stdin
相關的輸入流 通常,您想向用戶輸出提示:
std::cout << "Please enter your test input:\n";
然后,您要創建一個std::string
,並使用std::getline
和std::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.