Salem 5,265 Posting Sage

It works because it starts off by doing *p='\0'; to initialise a very small counter to zero.

It's basically using a position in the array as a temporary counter before overwriting it with the modified string.

It does however run into serious problems if the number of characters after the first 's' is more than can be represented in the positive part of a char (say 127 or 255 typically). As soon as that wraps around, then it's bye bye code.

> but to my faculty who had asked the original question..
Is that the same person who told you to use gets() ?

Perhaps you could point out these bugs to your tutor.

Salem 5,265 Posting Sage

> i 'll say Yes and No i.e It has been asked by my teacher but not as homework.
So there's no real harm whether you get an answer or not if there are no marks at stake.

What do you get if you show someone elses answer - a pat on the back for having 'leet' google and/or web forum nagging skills?

Post your best effort so far (say you've managed to get it down to just one variable), then perhaps we can suggest what else you can do.

> I am in a hurry u know !!
I'll post it eventually.

Salem 5,265 Posting Sage

Heh, that was an interesting problem.

> 1) You do not wish to use ANY local variables at all, so the only variable allowed in the function is the pointer to the string.
Check.

> 2) Using another function is not allowed.
Check.

> 3) You want to remove all 'S' characters, not just the first with this function.
Check.

In the words of deep thought "Tricky, but I think I can do it".

Also in the words of deep though "I have an answer, but you're not going to like it".

I've PM'ed it to WaltP for verification.

Salem 5,265 Posting Sage

Please don't tell me that's followed by strcpy( cp, tbuff ); If it is, it's a bug.
There is no space for the \0 at the end of the string.

1. In C++, it would be cp = new char[ strlen(tbuff) + 1]; 2. If you're REALLY converting it to C++ (and not just making it compile with C++), then you should be using std::string for all these strings rather than messing about with (and getting it wrong) your own memory allocation.

SpS commented: Right ~~ SunnyPalSingh +3
Salem 5,265 Posting Sage

> typedef int **ppMYARRAY[7]; Thats array of [7] pointers to pointers to int typedef int *(*ppMYARRAY)[7]; pointer to an array of [7] pointers to int

There's a program to help with the complicated ones.
http://packages.debian.org/stable/devel/cdecl

Here's an article on how to read those complex beasties.
http://www.codeproject.com/cpp/complex_declarations.asp

JoBe commented: Thanks for those links Salem +3
~s.o.s~ commented: Impressive, you live upto your reputation Mr. Salem - ~s.o.s~ +7
Salem 5,265 Posting Sage

> void printarray(int **,int);
> void printarray(int *array[],int);
Neither of these are valid for passing a true 2D array.

void foo ( int **p ) {
}
void bar ( int *p[] ) {
}
void baz ( int p[][7] ) { // p[3][7] would also work
}
void qux ( int (*p)[7] ) {
}

int main() {
    int L[3][7];
    foo(L);
    bar(L);
    baz(L);
    qux(L);
    return 0;
}

$ gcc foo.c
foo.c: In function `main':
foo.c:12: warning: passing arg 1 of `foo' from incompatible pointer type
foo.c:13: warning: passing arg 1 of `bar' from incompatible pointer type
Salem 5,265 Posting Sage

> how am i suppose to get the 9th bit??
There are only 8 bits.

Also, you only need ONE carry bit, not 8 separate ones.

Salem 5,265 Posting Sage

> printf(" user time: %d microseconds\n", sutime);
Go read the manual page for printf conversions again - %d is NOT for doubles.

If you're using gcc as your compiler, then add these flags to the command line gcc -W -Wall prog.c It will then tell you when the printf/scanf format doesn't match the parameters you pass.

Line commented: Thanks for the help! ;o) +1
Salem 5,265 Posting Sage

So if you want at most 100 chars, then it would be

char *stack = malloc ( max * sizeof *stack );
base = 0;
limit = max;

Adding stuff is stack[base++] = newValue; Checking is just if ( base == limit )

Salem 5,265 Posting Sage

> char *stk_layer[100];
But this isn't 100 characters

You could compare current with 100

But what is depth for?

Salem 5,265 Posting Sage

By providing a member function for your stack abstraction class which returns 'isFull'.

Stacks normally have no upper bound to the amount they can store, so perhaps the first thing you get to notice is an exception.

Salem 5,265 Posting Sage

Split from http://www.daniweb.com/techtalkforums/thread15252.html
Don't bump old threads.

Please use the tags in future.

Also, we need a better description than "it doesn't work".

Salem 5,265 Posting Sage

Why did you make it static?

It makes ALL the accounts have the same annual interest rate, and that's simply not true in the real world.

You need this just before your main

float SavingsAccount::annualInterestRate = 0;

> using namespace std;
Putting this in a header file is very bad form.
Anyone who includes the file will get the whole namespace whether they like it or not.

hoosier23 commented: very smart +1
Salem 5,265 Posting Sage

> i want to write a program which could convert given temperature and its unit into oher scales
Start with centigrade to centigrade.

Very trivial conversion, but it at least gets you to attempt the first part of actually attempting the "prompt the user and get answers" part of the program.

Then we at least will know which part of the problem you're really stuck on and we can advise accordingly.

Salem 5,265 Posting Sage

See also http://www.daniweb.com/techtalkforums/thread56253.html
> usingnamespace std;
Now I don't know whether this is an endemic problem with your coding, but it should be using namespace std; , that is, there is a space in there.

Now maybe it's you or maybe it's some damn fool code colouring script you're running which is bugged to hell and back. Either way, it's not helpful to have to second guess what the difference is between what you posted and what we see.

Just post your code between

tags, direct from your source code editor. We don't need colouring in a variable width font if the price is mangled code. Keep it nice and simple in a monospaced font.

Salem 5,265 Posting Sage

Mmm

$ dir
 Volume in drive C has no label.
 Volume Serial Number is F8A8-3449

 Directory of C:\temp

25/09/2006  19:00    <DIR>          .
25/09/2006  19:00    <DIR>          ..
25/09/2006  18:58                 2 my long filename.txt
               1 File(s)              2 bytes
               2 Dir(s)  13,895,516,160 bytes free

$
$ copy "my long filename.txt" test.txt
        1 file(s) copied.

$ command.com
Microsoft(R) Windows DOS
(C)Copyright Microsoft Corp 1990-2001.

$ copy "my long filename.txt" test2.txt
        1 file(s) copied.

$ exit

Maybe it's just enough if you surround the long filename with double quotes.
But bear in mind that command.com also has a limit (like 128 characters) on the length of any command line, so there could still be problems.

Salem 5,265 Posting Sage

Well judging from the colour scheme from your output examples, my guess is you're using some crusty old Turbo C compiler on a nice new XP based system.

Problem number 1
Turbo C knows nothing about long filename, nor filenames with spaces.

It should be paying attention to the COMSPEC environment variable (which should be say ComSpec=C:\WINDOWS\system32\cmd.exe but I guess your compiler sets it to the far inferior command.com (because that's the historic answer for the historic compiler. Command.com didn't know anything about long filenames or space in filenames either.

And this is only one of many possible compatibility problems you'll face with this compiler.

Get a modern 32-bit compiler, one which is far more compatible with your operating system.

Salem 5,265 Posting Sage

> cout << copier;
Why didn't this appear to output anything?

> system(copier);
If the string is garbage in any way, then you'll get that error message.

> string my_copy = "copy" ;
> my_copy += " " + lectut_loca + " " + lectut_name ;
Starting with a string constant is perhaps a bad idea. + is oveloaded for both char * pointer addition (the type of " ") and std::string concatenation (your strings). The compiler might pick the wrong one.
Try

string my_copy = "copy " ;
my_copy += lectut_loca + " " + lectut_name ;
Salem 5,265 Posting Sage

Error messages come with line numbers.
Use those line numbers to find out where in the code the problem is. Any editor should have a "goto line" feature, or at least display line numbers in some manner.

Post code (annotated with line numbers if necessary) along with exact error messages if you're still stuck.

Salem 5,265 Posting Sage

> void fun(int **array)
The rule about arrays become pointers is not recursive - it only happens for the outermost level of the array. void fun ( int (*array)[40] ); is one way to declare the function.

This is another way, which is easier to remember since it's just copy/paste of the original array that you want to pass in the first place. void fun ( int array[40][40] ); Either form is equivalent, and you can of course use [row][col] indexing on the array inside the function just as you would outside the function.


Yes, main does return an int by the way.

Salem 5,265 Posting Sage

> gives me the correct output but why is this?
Because scanf() is full of wonderful surprises - the most usual being that it leaves the \n on the input stream - just ready for the getchar() to return with immediate success.

I'd suggest you ALWAYS use fgets() to read a line of input, then use sscanf() (or something else) to extract information from the buffer.
fgets() leaves the input stream in a far more consistent state than scanf() ever can.

char buff[BUFSIZ];
if ( fgets( buff, sizeof buff, stdin ) != NULL ) {
  if ( sscanf( buff, "%d %[abcdefg] %s", &i, str, str2) == 3 ) {
    printf("%d %s %s\n", i, str, str2); 
  } else {
    // some error
  }
}
Salem 5,265 Posting Sage

> Listen, I don't speak c++, I don't really care what you c++ rabis debate about evry day.
Why are you here - really?
It can't be to actually learn anything because you're just being a bonehead about learning anything new. You're just after a quick fix to get past the current problem and be damned to the future.

Great - you've got your free cookie, now go back and enjoy your Pascal for a few more years.

> Thanks for the advice anyways,
But you're just going to ignore it because you've latched onto the first thing which "works for me" and you're happy?

If you don't want advice, don't ask for it.

Salem 5,265 Posting Sage

> is because windows functions only accept char*,
So how do you know that those functions are not going to modify the string?

Now some windows functions are sloppy in the use of const, but then again perhaps they're not const for a reason. Since you're being vague about what it is you're trying to do, we'll just have to guess.

The only safe way out is something like

char *foo = new char[ str.length() + 1 ];
strcpy( foo, str.c_str() );  // make a copy you know you can change
someAPICall ( foo );  // some function which doesn't like const
delete [] foo;

> No it works, i tried it.
Today, maybe, with your current compiler and particular program.
Long term, in the future, you're gonna get bitten really hard when you least expect it (mostly near a deadline).

Programming is a habit of doing the right thing when it doesn't matter so you'll do the right thing when it does matter. The attitude of "works for me" won't wash long term.

Sometimes, people really do have to fall off a cliff just to figure out gravity exists. Enjoy your future flight.

Salem 5,265 Posting Sage

A better question is why you're still so desperate to cling to a char* when you're using C++ strings.

c_str() returns a const char * for a reason, that reason being you shouldn't be using it to modify the underlying std::string. If you make that const go away with a cast, then sneakily (or more likely accidentally) modify it, then the whole game is over. Your pointer might not even be valid any more (the std::string has deleted itself), or it could be pointing at something else (the std::string has moved).

It's meant for doing things like passing const char * parameter values to historic interfaces which expect a const char *

std::string filename = "foo.txt";
std::ifstream in.open( filename.c_str() );

Keeping one for yourself to do whatever is just inviting later disaster IMO.

Salem 5,265 Posting Sage

> It works now,
You mean
"It works for now"

> I type casted the str2.substr().
If you needed a cast to get out of such a small problem, then you've almost certainly done the wrong thing and you're in for problems later on.

Salem 5,265 Posting Sage

As if bumping an old thread wasn't bad enough, you had to use gets() and atoi() to do it.

Dave Sinkula commented: Fixing erroneous neg rep. +13
Salem 5,265 Posting Sage

Because WSAStartup() and WSACleanup() are like { and }

They SURROUND the body of code which does network API calls.

Calling cleanup takes you back to the state you were in before you called startup, which is why you get the error that startup hasn't been called.

Salem 5,265 Posting Sage

> It never outputs that the startup has failed, so I don't believe that's the problem...
I bet the following call to cleanup() before you get to do any real work has something to do with it.

Salem 5,265 Posting Sage

> Why the reverse output?
Make sure you understand the consequences of the link posted by WaltP

Even though you might be able to come up with an explanation of why the output is reversed, there is no telling what would happen in any similar circumstance.

Undefined behaviour is very specific, anything at all can happen and the problem is solely with your code. It is not a language issue or a compiler issue.

Salem 5,265 Posting Sage

> The reason for this error might be that I am not allocating any memory for the pointer(correct me if I am wrong).
Yes, it has been allocated, but the memory which you're pointing at is read-only (meaning you can't change it). The variable p can be changed (say p="world"), but what it points at cannot be changed (you get the error).

> 1) Will the compiler places the string "name" in the stack segment of the memory
No, only p is on the stack, the string is somewhere else, allocated by the compiler.
In effect, the compiler does this for you. You just never see (or know) the name of the array it creates.

const char anon[] = "hello";
int main(void)
{
 char *p = anon;
 p[0] = 's';
 printf("%s", p); 
}

If you want something you can change, try

int main(void)
{
 char hello[] = "hello";
 char *p = hello;
 p[0] = 's';
 printf("%s", p); 
}

Both your pointer and string are on the stack, and you can change the string via your pointer.

> 2) Will the string "name" be in the stack???
No, see above.

> 3) If that is the case why I am getting the error at the run time. The memory is anyhow allocated to the string.
Because the 'anon' string itself is not WRITEABLE.
Yes, it is allocated, no you can't change it.

> void main(void)
main returns an …

Salem 5,265 Posting Sage

> while(charbuff!=' ')
Maybe this is false on the first iteration, therefore i never gets modified and the function exits without doing anything.

> ........... some code
Post COMPLETE whole programs which show the problem.
Most efforts to snip out "irrelevant" code usually end up snipping out something really vital to the question at hand. This seems to be no exception.

Salem 5,265 Posting Sage

> for( i = 0, j = 5; i<5; i++,j--)
The last element of the array is at index 4, not index 5

for ( i = 0 ; i < 5 ; i++ ) // going forwards
for ( i = 4 ; i >= 0 ; i-- ) // going backwards

Salem 5,265 Posting Sage

> looking at ur requierment, u can write in swap funtion like
What is wrong with using a temporary variable?

Not to mention the possibility of data corruption due to whatever way you machine handles arithmetic overflow and underflow.

Salem 5,265 Posting Sage

It isn't even valid C, never mind C++.

I don't know which crusty old fossil compiler you're using (but I guess it's Turbo C), but you seriously need to upgrade to something in this century.

Here are a bunch of edits just to make the thing compile using a C compiler.
Watch out for all the !! comments.

#include<stdio.h>
/*!!#include<conio.h> non-standard header */
/*!!#include<io.h> non-standard header */
/*!!#include<fcntl.h> non-standard header */
#include<string.h>
#include<stdlib.h>
/*!!#include<alloc.h> non-standard header */
/*!!#include<dos.h> non-standard header */

/*!! stubs for non-portable functions */
/*!! write these using portable code */
void clrscr ( void ) {
}
int getch ( void ) {
  return 0;
}

/*!! why so few parameters, and why so many globals? */
int display();
long int getsize(char[]);
void editb();
void edits();
void bkst();
void stst();
void issue();
void viewret();
void retbook();
void bklt();
void stlt();

/*!! added */
/*!! which crusty old DOS header did you get this from? */
struct date {
  int da_year;
  int da_mon;
  int da_day;
};
/*!! end add */

typedef struct date DATE;

DATE dt,is,rt;
int dtest;

typedef struct
{
  char sno[6];
  char name[20];
  float fine;
  char dept[3];
  int token;
}student;

typedef struct
{
  char bno[5];
  char bname[50];
  char aname[20];
  DATE iss;
  DATE ret;
  char status[1];
  char isto[6];
  int cost;
  char descpt[200];
}book;

int id,im,iy,rd,rm,ry;

void assign(book *b)
{
  b->iss.da_year=iy;
  b->iss.da_mon=im;
  b->iss.da_day=id;
  b->ret.da_day=rd;
  b->ret.da_mon=rm;
  b->ret.da_year=ry;
  return;
}

/*!! bunch of functions which are NOT implemented */
/*!! we can't review code if …
Salem 5,265 Posting Sage

Gee, normally noobs ask for help to finish their homework.
Now they're too helpless to even think of a name for it, nevermind do it :rolleyes:

Salem 5,265 Posting Sage

> version creates 'x' as a const pointer object.
When you've finished reading this
http://c-faq.com/aryptr/constptr.html

Finish reading this
http://c-faq.com/aryptr/index.html

Salem 5,265 Posting Sage

> if ((year % 400)==0)
How is this even compiling, when all you have is a parameter called 'y' ?

> return 0;
How is this even compiling, when you declared it as returning void?

Salem 5,265 Posting Sage

Can you paste a log of your run, showing the prompts being printed and the values you typed in?

Salem 5,265 Posting Sage

> char month[13]
Try

char *month[12]={"January","Febuary","March", "April", "May", "June", "July", "August", 
"September", "October", "November", "December"};

> cout << month << " " << day << " " << year << "\n";
You also need to actually call the function as well, say printMonth( month );

Salem 5,265 Posting Sage

> But, I didn't need to add a null pointer to the end of the string. It works anyways.
1. It's a NUL char, not a NULL pointer.
2. Yes, you do need to add it, otherwise you're relying on the buffer being initialised (which it isn't).
On the other hand, you could be sending the \0 (either by accident or by design).

Wanna see?
Try

memset( buffer, 0xff, sizeof(buffer);  /* very specific non-zero fill */
sr = recv(acc, buffer, sizeof(buffer)-1, 0);
cout << "sr = " << sr << "\n";
buffStr = buffer;

Now see whether buffStr is correct or not?

Salem 5,265 Posting Sage

> The output of sr is 1, which is not the size of the buffer
Who said it would be?
The size you pass is "don't go past this many characters", not "please hang around until you fill the buffer".
You got 1 character, so copy it to somewhere else, and call recv() again.
Keep calling it until you have all your data.

Salem 5,265 Posting Sage

> int sr = recv(acc, buffer, sizeof(buffer), 0);
1. recv doesn't store a \0 on the end to make it a proper string
2. You need to leave room to store the \0 yourself
3. You need to code for the possibility that recv() doesn't receive the whole message in one go (if this is a TCP connection)

int sr = recv(acc, buffer, sizeof(buffer)-1, 0);
if ( sr > 0 ) {
  buffer[sr] = '\0';  /* make it a string */
  /* now you can do str... operations on buff */
}
SpS commented: Agree:sunny +1
Salem 5,265 Posting Sage

> strcpy(sendBuffer, temp.c_str());
If you're going to do this, why are you bothering with 'C' strings at all?

Salem 5,265 Posting Sage

> cin >> inp[40];
The next problem is you're inputting only a single char, but its off the end of your array.

cin >> inp;
Would input a single word into your array.

> inp[k] = '\n';
This loop does nothing useful.

> if (trade(word == '\n'))
This performs a comparison, and then passes the boolean result 0 or 1 to the trade function.
Is this what you wanted?

Salem 5,265 Posting Sage

> y = y>>8;
Right shift of negative numbers is implementation defined.
On some systems, the sign bit is propagated
11110000 would become 11111000

and on others zero is inserted.
11110000 would become 01111000

Salem 5,265 Posting Sage

Well did you open the file for output in binary mode?
Did you check the sizes of the file on the two different systems was the same?
Have you copied a file generated on your Linux box to the windows box, and tried to play that?

Salem 5,265 Posting Sage

> cout << "Type 1 to exit or 0 to continue." << endl;
> cin >> exit;
Put these two lines inside your inner while loop, so you ask after each response.

> while (!correct)
Change to
while (!correct && !exit)

exit is also the name of a function in cstdlib, so you might want to change the name of your local variable to save a bit of weirdness later on.

Salem 5,265 Posting Sage

> if ( filename == "day_01.txt")
Use if ( strcmp( filename, "day_01.txt" ) == 0 )

Rashakil Fol commented: Hello Salem! +1