473,734 Members | 2,693 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a little mistake

ash
i am writing this program (for exercise1-9 in k&r-2nd edition) which
removes extra spaces in string
example- "test string" will be "test string"

#include<stdio. h>
#include<string .h>
#include<conio. h>
main()
{
char str[20],st[20];
int i=0,j=0;
printf("enter string");
gets(str);

while(str[i]!=NULL)
{
if(str[i]==' ')
{ st[j++]=st[i++];

while(str[i]==' ') i++;

}
else
st[j++]=str[i++];
}
st[j]=NULL;
strcpy(str,st);
puts(str);
}

(compiled in turbo c++ for windows version 3.1)
i know there should be other ways to write this program (thats a bad
program ),can someone help me in writing that program in compact way
and give me some logic and tips.
i want to use gcc but i don`t have linux operating system and one
software which allows gcc compiling in windows (cygwin) is not working.
anyone can advice me such a program that allows compiling with gcc in
windows( this is off topic but advices are always welcome).

thankx

Jun 16 '06 #1
54 2993

"ash" <as************ @rediffmail.com > wrote in message
news:11******** **************@ i40g2000cwc.goo glegroups.com.. .
i am writing this program (for exercise1-9 in k&r-2nd edition) which
removes extra spaces in string
example- "test string" will be "test string"

#include<stdio. h>
#include<string .h>
#include<conio. h>
main()
{
char str[20],st[20];
int i=0,j=0;
printf("enter string");
gets(str);

while(str[i]!=NULL)
{
if(str[i]==' ')
{ st[j++]=st[i++];

while(str[i]==' ') i++;

}
else
st[j++]=str[i++];
}
st[j]=NULL;
strcpy(str,st);
puts(str);
}

(compiled in turbo c++ for windows version 3.1)
i know there should be other ways to write this program (thats a bad
program ),can someone help me in writing that program in compact way
and give me some logic and tips.
i want to use gcc but i don`t have linux operating system and one
software which allows gcc compiling in windows (cygwin) is not working.
anyone can advice me such a program that allows compiling with gcc in
windows( this is off topic but advices are always welcome).

thankx

Separate out ewhat you are doing into a function.

In this case you want

/*
turns whitespace spans into single spaces
(and trims leading / trailing white space?)
*/
void onespace(char *out, char *in)

Decide if you want to allow out and in to be the same. This will make your
function
more convenient to use, but you might have to be a little bit more careful
in coding it.

Basically you maintain two pointer, a "write" pointer and a "read" pointer.
If you hit
a non-whitespace you write to the "write" pointer and increment both.
If you hit a whitespace character, you write a single space to the "write"
pointer. Then you increment the "read" pointer whilst it is still pointing
to white space.
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm
Jun 16 '06 #2
ash wrote:
.... snip ...
i want to use gcc but i don`t have linux operating system and one
software which allows gcc compiling in windows (cygwin) is not working.
anyone can advice me such a program that allows compiling with gcc in
windows( this is off topic but advices are always welcome).


Generally Cygwin is a bit complex to set up and use. Use MinGW instead.
It uses native Win32 ports of the GNU toolchain.

http://www.mingw.org/

Jun 16 '06 #3
"ash" <as************ @rediffmail.com > writes:
i am writing this program (for exercise1-9 in k&r-2nd edition) which
removes extra spaces in string
example- "test string" will be "test string"

#include<stdio. h>
#include<string .h>
#include<conio. h>
<conio.h> is not a standard header. You don't use it anyway. Delete
the above line.

I find it clearer to leave a space between "include" and "<".
main()
int main(void)
{
char str[20],st[20];
int i=0,j=0;
printf("enter string");
Since this doesn't end in a newline, it's not guaranteed to appear.
Add "fflush(stdout) ;".

I'd add a blank, or perhaps ": ", at the end of the prompt; it looks
better. Without it, if I type "foo", I see "enter stringfoo" on the
screen.
gets(str);
Never use gets(). Never use gets(). Never use gets().

See question 12.23 in the comp.lang.c FAQ, <http://www.c-faq.com/>.
while(str[i]!=NULL)
NULL is a null pointer constant. You're trying to compare a character
value to a pointer value. It happens to work on your system for
obscure reasons I won't get into, but it's bad style at the very
least. The way to represent a null character is '\0'.
{
if(str[i]==' ')
{ st[j++]=st[i++];
I think you mean "st[j++]=st[i++];"

while(str[i]==' ') i++;

}
else
st[j++]=str[i++];
}
st[j]=NULL;
Again, use '\0', not NULL.
strcpy(str,st);
puts(str);
return 0;
}


And don't underestimate the importance of consistent formatting,
particularly indentation.

Apart from that, the program doesn't seem unreasonable.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 16 '06 #4
ash wrote:
i am writing this program (for exercise1-9 in k&r-2nd edition) which
removes extra spaces in string
example- "test string" will be "test string"
That's not the actual exercise:

Exercise 1-9. Write a program to copy its input to its output,
replacing each string of one or more blanks by a single blank.


#include<stdio. h>
#include<string .h>
#include<conio. h>
<conio.h> is not a standard header. You should not use it, as it's not
very portable.
main()
Use the following form:

int main(void)
{
char str[20],st[20];
These fixed buffers are likely a problem.
int i=0,j=0;
printf("enter string");
gets(str);
Never, ever use gets(). It's dangerous. What happens when someone
enters a string with 50 characters? Bad things.

while(str[i]!=NULL)
NULL is a null pointer constant. It might be 0, which would work, but
it could be (void*)0. Either use '\0' or 0 in checking for the null
terminator in a string.
{
if(str[i]==' ')
{ st[j++]=st[i++];

while(str[i]==' ') i++;

}
else
st[j++]=str[i++];
}
st[j]=NULL;
strcpy(str,st);
puts(str);
}

(compiled in turbo c++ for windows version 3.1)
i know there should be other ways to write this program (thats a bad
program ),can someone help me in writing that program in compact way
and give me some logic and tips.
i want to use gcc but i don`t have linux operating system and one
software which allows gcc compiling in windows (cygwin) is not
working. anyone can advice me such a program that allows compiling
with gcc in windows( this is off topic but advices are always
welcome).


Do you want the program that K&R assigned, or the one you tried? It can
be made much more simple by just immediately outputting characters
instead of copying to buffers.

/* algorithm portion */

int c;
int flag = 0;

while ((c = getchar()) != EOF)
{
if (c == ' ')
{
if (flag == 0)
{
putchar(c);
flag = 1;
}
}
else
{
if (flag == 1)
{
flag = 0;
}
putchar(c);
}
}

Brian
Jun 16 '06 #5
ash wrote:
.... snip ...
i want to use gcc but i don`t have linux operating system and one
software which allows gcc compiling in windows (cygwin) is not
working. anyone can advice me such a program that allows compiling
with gcc in windows( this is off topic but advices are always
welcome).


djgpp, at <http://www.delorie.com >. However cygwin should work.

--
"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews

Jun 16 '06 #6
Malcolm wrote:
"ash" <as************ @rediffmail.com > wrote in message
news:11******** **************@ i40g2000cwc.goo glegroups.com.. .
i am writing this program (for exercise1-9 in k&r-2nd edition) which
removes extra spaces in string
example- "test string" will be "test string"

#include<stdio. h>
#include<string .h>
#include<conio. h>
main()
{
char str[20],st[20];
int i=0,j=0;
printf("enter string");
gets(str);

while(str[i]!=NULL)
{
if(str[i]==' ')
{ st[j++]=st[i++];

while(str[i]==' ') i++;

}
else
st[j++]=str[i++];
}
st[j]=NULL;
strcpy(str,st);
puts(str);
}

(compiled in turbo c++ for windows version 3.1)
i know there should be other ways to write this program (thats a bad
program ),can someone help me in writing that program in compact way
and give me some logic and tips.
i want to use gcc but i don`t have linux operating system and one
software which allows gcc compiling in windows (cygwin) is not working.
anyone can advice me such a program that allows compiling with gcc in
windows( this is off topic but advices are always welcome).

thankx

Separate out ewhat you are doing into a function.

In this case you want

/*
turns whitespace spans into single spaces
(and trims leading / trailing white space?)
*/
void onespace(char *out, char *in)

Decide if you want to allow out and in to be the same. This will make your
function
more convenient to use, but you might have to be a little bit more careful
in coding it.

Basically you maintain two pointer, a "write" pointer and a "read" pointer.
If you hit
a non-whitespace you write to the "write" pointer and increment both.
If you hit a whitespace character, you write a single space to the "write"
pointer. Then you increment the "read" pointer whilst it is still pointing
to white space.


I think you also need a little state machine: if you have not hit
a blank you are in character-accepting mode and write that char
to the buffer where you construct the compacted string. Otherwise
if the char is a blank you accept it but shift to a mode where you
no longer accept blank characters. When you hit a non-blank you
switch back to the first mode. In other words,

state\input -> non-blank blank
// --------------------------------------------------------
1 write to buff write to buff and
set state to 2

2 write to buff and drop char
set state to 1
// --------------------------------------------------------

A switch statement and a state variable will accomplish this.
--
Julian V. Noble
Professor Emeritus of Physics
University of Virginia
Jun 17 '06 #7
ash wrote:
can someone help me in writing that program in compact way
and give me some logic and tips.

I don't know whether my program is compact or not, anyway code below
it's my own. Suggestion welcomed.
/* Removes extra spaces in string pointed by src, the result string is
pointed by dst. Return value is the length os the result string or
0 for failure. example: "test string" will be "test string" */
int spacerm(char *dst, char *src)
{
int last_space = 0; /*1: last char is a space char; 0: not*/
int len = 0;
int ret = 1; /*for return value, 0: failure, non-zero: result
string length returned*/

if (src == 0 || dst == 0)
{
ret = 0;
}

if (ret != 0)
{
while (*src != '\0')
{
if (*src == ' ')
{
if (last_space != 1)
{
*dst++ = *src++;
len++;
}
else
{
src++;
}

last_space = 1;

}
else
{
*dst++ = *src++;
len++;
last_space = 0;
}
}

ret = len;
}

return ret;
}

#include <stdio.h>
#include <string.h>
int main(void)
{
char *s = "test string";
char a[20] = {'\0'};
int i = 0;

printf("%i, %s\n", strlen(s), s);
i = spacerm(a, s);
printf("%i, %s\n", i, a);

return 0;
}

$ gcc -W -Wall -pedantic -ansi test.c
$ ./a.out
14, test string
11, test string
$

i want to use gcc but i don`t have linux operating system and one
software which allows gcc compiling in windows (cygwin) is not working.
anyone can advice me such a program that allows compiling with gcc in
windows( this is off topic but advices are always welcome).

Use mingw or Install a Debian Linux on VMware hosted in Windows.

lovecreatesbeau ty

Jun 17 '06 #8
lovecreatesbeau ty wrote:

/* Removes extra spaces in string pointed by src, the result string is
pointed by dst. Return value is the length os the result string or
0 for failure. example: "test string" will be "test string" */
What if the original string is "". Is that an error? If so, why?
int spacerm(char *dst, char *src)
{
int last_space = 0; /*1: last char is a space char; 0: not*/
int len = 0;
int ret = 1; /*for return value, 0: failure, non-zero: result
string length returned*/
You effectively have two variables for the same thing. This
looks clumsy.
if (src == 0 || dst == 0)
Why bother? [Rehtorical]
{
ret = 0;
}

if (ret != 0)
{
while (*src != '\0')
{
if (*src == ' ')
{
if (last_space != 1)
if (last_space == 0)

Apart from being more efficient on many systems, it's
obvious what the test is. When you test explicitly against
a value like 1, the reader may pause to ponder whether
the variable can other values like 2 or 3 and why 1 is
significant.
{
*dst++ = *src++;
len++;
}
else
{
src++;
}

last_space = 1;

}
else
{
*dst++ = *src++;
len++;
last_space = 0;
}
}
You never write a terminating null byte to dst.
ret = len;
}

return ret;
}

#include <stdio.h>
#include <string.h>
int main(void)
{
char *s = "test string";
char a[20] = {'\0'};
Try...

char a[20] = "xxxxxxxxxxxWha t?";
int i = 0;

printf("%i, %s\n", strlen(s), s);
strlen() returns a size_t value; %i expects an int.

In C99 use %zu to print a size_t. In C90, cast the value
to suitable unsigned type and use %u with an appropriate
length modifier.
i = spacerm(a, s);
printf("%i, %s\n", i, a);

return 0;
}

$ gcc -W -Wall -pedantic -ansi test.c
Not a blip eg? Safe as houses then.

As some non-expert whose comments aren't worth the
em waves they're transmitted in once said "You control
the portability of your code, not gcc." <g>
$ ./a.out
14, test string
11, test string
$


--
Peter

Jun 17 '06 #9
ash posted:
i am writing this program (for exercise1-9 in k&r-2nd edition) which
removes extra spaces in string
example- "test string" will be "test string"

I'd probably approach it something like:

#include <cstddef>

void RetreatStrXPlac es(register char *p, std::size_t const places)
{
/* Consider coding this by copying int's
and checking if any byte is a space
character */

if ( !places ) return;

register char *q = p - places;

while ( *q++ = *p++ );
}

void FixMultipleSpac es( char * const p_start )
{
for(char *p = p_start; ; )
{
switch( *p++ )
{
case 0: return;

case ' ':
{
unsigned places = 0;

while( *p++ == ' ' ) ++places;

RetreatStrXPlac es(--p, places);
}
}
}
}

#include <iostream>
#include <cstdlib>

int main()
{
using std::cout;

char buffer[] = "The man walked over the revine";

FixMultipleSpac es(buffer);

cout << buffer << '\n';

std::system("PA USE");
}

--

Frederick Gotham
Jun 17 '06 #10

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

Similar topics

14
1851
by: Henk | last post by:
Hi Guys, (see actual code below) I wrote a little program that is supposed to read a file (input.txt) into memory (using a stack) and then reverse the file and display it to output. It works, but I still get some errors when i try to compile it: stack.c: In function 'reverseFile'
2
1295
by: Jesper. | last post by:
Hi, I'm a former C++ programmer, and normally I didn't see the use of the this pointer (pointer in c++) used as often as I see it in C#. When the VS generates code for you it uses >this< all the time. Examples I study in different newsgroups uses >this< all the time - like the example below. Why is >this< used so extensively when it is not required? (like in the example below) - if it is required then why?
9
8853
by: Eric S. | last post by:
Why doesn't something like this work? I get "a constant value is expected" on all 3 case statements. private DataGrid CurrentDataGrid(DataGrid firstDg, DataGrid secondDg) { try { switch (true) { case firstDg.Items.Count != 0 & secondDg.Items.Count != 0:
14
1528
by: tranky | last post by:
Hi, i'm italian...so...excuse me for my english. I've a little problem....in what manner i can check a textbox for know if it contain only character from A-Z (a-z), numbers (0-9), and underscore (-) and dot (.) ?!?!?!? I use vb.net. thank to all.
16
1772
by: mdh | last post by:
Can someone look at this little program and tell me why the last line is not compiling. #include <stdio.h> int main (){ int i, j, k; i=0;
13
27299
by: junky_fellow | last post by:
Hi guys, I need to convert a big endian integer to little endian integer. (the integer is 4 bytes in size on my implementation). I came up with the following code. I need your comments on this. Please suggest any improvements that can be done. #include <stdio.h> int main(void) {
4
2306
by: Batmanuel | last post by:
Good evening people, little question here... I'm trying to get this file upload script to work but it tells me that move_uploaded_file() fails because it doesn't have permission for the /tmp directory where the file is before the move. I would chmod /tmp itself but wouldn't that be a big security risk? is there another solution? Thanks for any help you can provide...
6
1617
by: djm | last post by:
hello everyone, im doing a c++ coursework which consists linked lists and use of classes. but im getting some compilation errors. can some please help me out. //this is the header file Definition.h #ifndef DEFINTION_H #define DEFINITON_H #include <string> using namespace std;
7
1726
by: CuTe_Engineer | last post by:
hii, can you tell me plzz why my programme doesn`t work ,i don`t have any errors and every thing is fine but i don`t know why it`s not working , soo plz can you help me un finding my mistake i will past the proramme here , the headers,
0
9449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9310
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.