我試圖做一個函數,過濾出一個句子中的所有標點和空格,並只返回新字符串中的字母和數字。功能不返回所需的字符串
ex。如果我輸入:嗨,我的名字是Zach1234。 我希望它只返回:himynameiszach1234
但它只是返回只有第一個字母。 有關如何解決此問題的任何想法?
#include <iostream>
#include <cctype>
using namespace std;
string filter(string str)
{
string result = "";
for(int i = 0; i < (str.size()-1); i++)
{
if(isspace(str[i]))continue;
if(ispunct(str[i]))continue;
if(isdigit(str[i]))result += str[i];
if(isalpha(str[i]))result += str[i];
}
return(result);
}
int main()
{
string happy;
cout <<"Please enter a string\n";
cin >> happy;
cout << filter(happy) << endl;
return(0);
}
首先你應該使用'getline()'來讀入輸入中的空格。 – NathanOliver
@NathanOliver正是這個問題,你應該發表一個答案 – vsoftco
它不會讓我接受我自己的答案兩天 –