问题描述
我正在尝试制作一个程序来从
输入文本中取出非字母字符...但是''ntext''总是比字母大4个字符
j ...为什么?
更好的方法吗?谢谢很多人。
void main()
{
int i,j = 0;
char text [9999];
char * ntext;
得到(文本);
for(i = 0 ; text [i]; i ++){
if(isalpha(text [i]))
j ++;
}
ntext = new char [j];
cout<< j<<" "<< strlen(ntext);
for(i = 0,j = 0; text [i]; i ++){
if(isalpha(text) [i])){
ntext [j] = text [i];
j ++;
}
}
strcpy(text,ntext);
cout<< endl;
for(i = 0; text [i]; i ++)
cout<< endl<< text [i];
delete [] ntext;
}
i''m trying to make a program to take out non alpha characters from
entered text...but ''ntext'' is always 4 char larger than the size
j...why is that?
any better ways to do this? thanks lots people.
void main()
{
int i, j=0;
char text[9999];
char *ntext;
gets(text);
for (i=0; text[i]; i++){
if(isalpha(text[i]))
j++;
}
ntext=new char [j];
cout<<j<<" "<<strlen(ntext);
for (i=0, j=0; text[i];i++){
if (isalpha(text[i])){
ntext[j]=text[i];
j++;
}
}
strcpy(text, ntext);
cout<<endl;
for (i=0; text[i]; i++)
cout<<endl<<text[i];
delete [] ntext;
}
推荐答案
问题依然存在。
您没有为ntext设置空字符
。并且你试图从ntext复制
。
考虑使用C ++字符串。你不会因为所有这些麻烦而感到尴尬。
The problem remains the same.
You are not setting the null character
for ntext. and you are trying to copy
from ntext.
Consider using C++ strings. You won''t
have all these troubles.
您可能想调查类''std :: string''和
算法''std :: remove()''。以下是使用C ++的
代码的道德等价物:
| #include< iostream>
| #include< string>
| #include< algorithm>
| #include< ctype.h>
|
| bool notalpha(char c)
| {
| return!std :: isalpha(static_cast< unsigned char>(c));
| }
|
| int main()
| {
| for(std :: string line; std :: getline(std :: cin,line);)
| {
| std :: string tmp(line);
| tmp.erase(std :: remove_if(tmp.begin(),tmp.end(),notalpha),
| tmp.end());
| std :: cout<< tmp<< " \ n";
| }
| }
-
< mailto:di *********** @ yahoo.com> < http://www.dietmar-kuehl.de/>
< http://www.contendix.com> - 软件开发&咨询
You might want to investigate the class ''std::string'' and the
algorithm ''std::remove()''. Here is the moral equivalent of your
code using C++:
| #include <iostream>
| #include <string>
| #include <algorithm>
| #include <ctype.h>
|
| bool notalpha(char c)
| {
| return !std::isalpha(static_cast<unsigned char>(c));
| }
|
| int main()
| {
| for (std::string line; std::getline(std::cin, line); )
| {
| std::string tmp(line);
| tmp.erase(std::remove_if(tmp.begin(), tmp.end(), notalpha),
| tmp.end());
| std::cout << tmp << "\n";
| }
| }
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting
如果你将''|''/ $
更改为/ ** /?然后我们可以复制/粘贴和编译。
-Mike
Will google post that correctly if you change the ''|''
to /**/ ? Then we could copy/paste and compile.
-Mike
这篇关于某事错了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!