【发布时间】:2016-07-21 14:40:15
【问题描述】:
嘿,我对编程很陌生,在我的程序中使用 isalpha 函数时遇到了问题。这是回文类代码的一部分。我想要做的是从输入中删除所有非字母字符。因此,如果用户输入“嗨,你好吗”,我需要首先计算仅包含字母的数组的大小,然后在我的 removeNonLetters 子类中,我需要去掉非字母字符。有人可以帮我解决这个问题。非常感谢!
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <cctype>
#include <cstring>
#include <ctype.h>
using namespace std;
class palindrome
{
private:
int only_letters_size;
string input_phrase;
string* only_letters;
public:
string inputPhrase();
string removeNonLetters();
string* new_Array;
int size_new_Array;
};
string palindrome::inputPhrase()
{
cout << "Input phrase: "; //asks the user for the input
getline(cin,input_phrase);
size_new_Array = input_phrase.length(); //creating a dynamic array to store
the input phrase
new_Array = new string[size_new_Array];
int i;
for (i=0; i<size_new_Array; i++)
{
new_Array[i]=input_phrase[i];
}
only_letters_size = 0;
while(new_Array[i])
{
if (isalpha(new_Array[i])) //PROBLEM OCCURS HERE
{
only_letters_size=only_letters_size+1;
}
}
cout << only_letters_size << endl;
return new_Array;
}
string palindrome::removeNonLetters()
{
int j=0;
int str_length = new_Array.length(); //string length
only_letters = new string[only_letters_size];
for (int i=0;i<size_new_Array;i++) //PROBLEM OCCURS HERE AS WELL
{
if (isalpha(new_Array[i]))//a command that checks for characters
{
only_letters[j] = new_Array[i];//word without non alphabetical c
characters is stored to new variable
j++;
}
}
cout << only_letters << endl;
return only_letters;
}
【问题讨论】:
-
那么问题出在哪里?哪里有问题?为什么你认为我们必须阅读所有代码?你能调试你的程序吗?您能否删除所有不需要的代码并发布minimal reproducible example?
-
我相信你要分配的是
char[size_new_Array],肯定不是string[size_new_Array]? std::string 是多个字符的集合,您可以使用字符串数组,就好像 1 个字符串代表 1 个字符一样。动态分配是否需要?因为在这里使用一个简单的字符串就足够了。 -
您可能只需要更好地了解
std::string究竟是什么。 -
如果我使用它,我必须将所有字符串*更改为 char*?不,不需要动态分配。使用一个简单的字符串是什么意思? @AdnanElezovic
-
@JimmyKelly 要从
std::string访问单个字符,请使用 indexingoperator[]函数。
标签: c++ string class object palindrome