473,387 Members | 1,463 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

sth wrong?

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;
}

Jul 22 '05 #1
14 1426
Hello wrote:
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.
This can be definitely done better.
Get rid of c-style strings and you can use C++ string's ( <string> ).
This seems more like a C program than a C++ program.

void main()
{

int i, j=0;
char text[9999];
string text;

char *ntext;
gets(text);
use getline method of istream ( cin ).

There had been so many buffer overflows
thanks to gets. Do not use it.
for (i=0; text[i]; i++){
if(isalpha(text[i]))
j++;
}
ntext=new char [j];
Ok - you are allocating a chunk of memory
afresh.
cout<<j<<" "<<strlen(ntext);
And right away, you are trying to find
the length of the string.
Considering this as a C program,
this is still bad. where are you
setting the null character (that is the
delimeter that strlen looks for ).

for (i=0, j=0; text[i];i++){
if (isalpha(text[i])){
ntext[j]=text[i];
j++;
}
}
strcpy(text, ntext);


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.
Jul 22 '05 #2
Hello wrote:
void main()
There is no such thing as 'void main()'! Any compiler accepting
this code without a diagnostic is in error.
gets(text);
You shall *NEVER* use 'gets()'! It is the primary source for
security problems. The issue is that you cannot guarantee that
the array you give to 'gets()' is sufficiently large. Use
'fgets()' or, even better, 'std::getline()' instead (the member
function 'getline()' has a similar problem although it is
possible to setup a maximum width: it is just easy to forget
and thus this member function is error prone).
ntext=new char [j];
This is at least one character too small: you need space for a
terminating null character.
cout<<j<<" "<<strlen(ntext);
for (i=0, j=0; text[i];i++){
if (isalpha(text[i])){
ntext[j]=text[i];
j++;
}
}
.... and, of course, you need to add the terminating null
character before copying the new string somewhere:
strcpy(text, ntext);


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

Jul 22 '05 #3
"Dietmar Kuehl" <di***********@yahoo.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
| #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";
| }
| }


Will google post that correctly if you change the '|'
to /**/ ? Then we could copy/paste and compile.

-Mike
Jul 22 '05 #4
Mike Wahler wrote:
"Dietmar Kuehl" <di***********@yahoo.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
#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";
}
}


Will google post that correctly if you change the '|'
to /**/ ? Then we could copy/paste and compile.


Or he could post it compiled, and the we would only need to run it. ;-)

--
WW aka Attila
:::
I can resist everything but temptation. -- Oscar Wilde
Jul 22 '05 #5
Mike Wahler wrote:
Will google post that correctly if you change the '|'
to /**/ ? Then we could copy/paste and compile.

Let's give 'er a whirl:
/**/ 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";
/**/ }
/**/ }

Looks ok in the Preview, so it should be good for you.

Brian

Jul 22 '05 #6
"Default User" <de***********@yahoo.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Mike Wahler wrote:
Will google post that correctly if you change the '|'
to /**/ ? Then we could copy/paste and compile.

Let's give 'er a whirl:
/**/ 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";
/**/ }
/**/ }

Looks ok in the Preview, so it should be good for you.


Looks good here (OE6 in 'text mode'). Thanks for taking
the time.

I officially propose this as our new 'google defense'.

Now if I can figure out how to automate that in my
editor. :-)

-Mike
Jul 22 '05 #7
> 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.


In this case, I think C is as effective as C++:

int main() {
int ch;
while (EOF!=(ch=getchar()))
if (isalpha(ch)
putchar(ch);
return 0;
}

If you really want to use things specific to C++, you have a fair
number of choices though. Just for one exzample:

// Minimally tested
#include <iostream>
#include <algorithm>
#include <cctype>
#include <iterator>
#include <ios>

int main() {
std::noskipws(std::cin);
std::remove_copy_if(std::istream_iterator<char>(st d::cin),
std::istream_iterator<char>(),
std::ostream_iterator<char>(std::cout),
std::isalpha);
return 0;
}

I have a new ambition in life: to be able to write a program that
consists entirely of #include's, with no actual code at all. :-)

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 22 '05 #8

"Default User" <de***********@yahoo.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Mike Wahler wrote:
Will google post that correctly if you change the '|'
to /**/ ? Then we could copy/paste and compile.

Let's give 'er a whirl:
/**/ 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";
/**/ }
/**/ }

Looks ok in the Preview, so it should be good for you.

Brian


Unless, of coure, you include multi-line comments in your code. :-0

-H

Jul 22 '05 #9
Mike Wahler wrote:
[SNIP]
Now if I can figure out how to automate that in my
editor. :-)


Change start of line to /**/ in regexp search and replace. If your editor
does not know this throw it away, and start using NEdit (assuming some *nix
environment). ;-)

--
WW aka Attila
:::
Join the army. Meet interesting people. Kill them. -- Steven Wright
Jul 22 '05 #10
[ ... ]

// Minimally tested
#include <iostream>
#include <algorithm>
#include <cctype>
#include <iterator>
#include <ios>
int main() {
std::noskipws(std::cin);
std::remove_copy_if(std::istream_iterator<char>(st d::cin),
std::istream_iterator<char>(),
std::ostream_iterator<char>(std::cout),
std::isalpha);
return 0;
}

Perhaps I should have said "minimally, but totally incorrectly tested"
-- I managed to get the C version correct, but in the C++ version I got
the sense wrong -- instead of using isalpha directly, we need to use a
function to invert its sense (and, unfortunately, std::not1 won't
work). e.g.:

bool notalpha(char ch) {
return !std::isalpha((unsigned char)ch);
}

// ...
std::remove_copy_if( /* ... */
notalpha);

Sorry 'bout that...

--

Later,
Jerry.

The universe is a figment of its own imagination.

Jul 22 '05 #11
"White Wolf" <wo***@freemail.hu> wrote in message
news:cs**********@phys-news1.kolumbus.fi...
Mike Wahler wrote:
[SNIP]
Now if I can figure out how to automate that in my
editor. :-)

First of all, that remark was meant 'tongue-in-cheek', as
I don't post with google (shudder).

Change start of line to /**/ in regexp search and replace. If your editor
does not know this throw it away, and start using NEdit (assuming some *nix environment). ;-)


I wasn't thinking of an 'after the fact' fix, but a feature
that automatically added predefined text to each line as
I type, without any intervention on my part, like the old
MS-DOS editor 'BRIEF' (btw still my all time favorite editor)
could do.

-Mike
Jul 22 '05 #12
Mike Wahler wrote:
[SNIP]
I wasn't thinking of an 'after the fact' fix, but a feature
that automatically added predefined text to each line as
I type, without any intervention on my part, like the old
MS-DOS editor 'BRIEF' (btw still my all time favorite editor)
could do.


I guess NEdit can do that too. My favoriute was MultiEdit and something
called E!, which was a kind of programmable vi clone. The MultiEdit we had
(in DOS) was a beast which was completely programmed in its own macro
language. I mean the user interface, the menus and all.

--
WW aka Attila
:::
"Emacs is a nice operating system, but I prefer UNIX." - Tom Christiansen
Jul 22 '05 #13
"White Wolf" <wo***@freemail.hu> wrote in message
news:cs**********@phys-news1.kolumbus.fi...
Mike Wahler wrote:
[SNIP]
I wasn't thinking of an 'after the fact' fix, but a feature
that automatically added predefined text to each line as
I type, without any intervention on my part, like the old
MS-DOS editor 'BRIEF' (btw still my all time favorite editor)
could do.
I guess NEdit can do that too. My favoriute was MultiEdit and something
called E!, which was a kind of programmable vi clone. The MultiEdit we

had (in DOS) was a beast which was completely programmed in its own macro
language. I mean the user interface, the menus and all.


Sounds very similar to BRIEF. (I seem to recall the name is
an acronym: Basic Reconfigurable Interactive Editing Facility
-- now *that's* a mouthful! :-))

-Mike
Jul 22 '05 #14
thanks a lot people for the comments!

Jul 22 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Jay Levitt | last post by:
I'm just starting to play around with CSS and MovableType. My home page (http://www.jay.fm) now validates on both the CSS and the XHTML. However, the Google cached version shows the wrong font in...
7
by: Jerry Krinock | last post by:
I've declared a class that has some std::vector data members like this: class MyClass { public: ... std::vector<Apples> apples ; ... private: ...
5
by: titan0111 | last post by:
#include<iostream> #include<iomanip> #include<cstring> #include<fstream> using namespace std; class snowfall { private: int ft;
5
by: Krisnamourt Correia via SQLMonster.com | last post by:
I have one query that executes many times in a week. I created one Maintenances plan that Rebuild all index in my Database that has been executed at 23:40 Saturday until stop finished at Sunday. ...
6
by: Michael Sparks | last post by:
Hi, I suspect this is a bug with AMK's Crypto package from http://www.amk.ca/python/code/crypto , but want to check to see if I'm being dumb before posting a bug report. I'm looking at...
3
by: Soren Jorgensen | last post by:
Hi, Following code should give the number of weeks in years 1998-2010 for a Danish calendar (on a Danish box) GregorianCalendar cal = new GregorianCalendar(); for(int i = 1998; i < 2010; i++)...
8
by: Dmitry Korolyov | last post by:
ASP.NET app using c# and framework version 1.1.4322.573 on a IIS 6.0 web server. A single-line asp:textbox control and regexp validator attached to it. ^\d+$ expression does match an empty...
3
by: belton180 | last post by:
CODE]../* Program function: Simulate the stack using a stack limit of 10. Display a menu for the the following. Create a stack Insert an item in the stack Pop an item from the stack ...
318
by: jacob navia | last post by:
Rcently I posted code in this group, to help a user that asked to know how he could find out the size of a block allocated with malloc. As always when I post something, the same group of people...
3
by: Siong.Ong | last post by:
Dear all, my PHP aims to update a MySQL database by selecting record one by one and modify then save. Here are my PHP, but I found that it doesnt work as it supposed to be, for example, when...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.