Amiga.org

Amiga computer related discussion => Amiga Software Issues and Discussion => Topic started by: z5 on April 03, 2003, 05:20:02 PM

Title: I need help with C(++)
Post by: z5 on April 03, 2003, 05:20:02 PM
Hi!

i'm doing my exercises for my exam c(++). The compiler i use is Borland c++. I've run into this problem so i thought: why not ask on Amiga org ;-)

Here's the little program:
#include
#include
#include

void main(void)
  {
     const numberofstrings = 5;
     char str[numberofstrings][80],*p;
       
     for(p=str;p                {
                printf("Type string: ");
                gets(p);
                }
}

The problem is that my compiler doesn't allow p=str because str is a two dimensional array. I just wanted the pointer to point at the first string in my string array.

What i was trying to achieve is that the user gives a couple of strings and i store them in a string array (using pointers).

Thanks for any help
Title: Re: I need help with C(++)
Post by: Kronos on April 03, 2003, 05:34:09 PM
Sure but not so elegant solution:

p = &str[0][0];
Title: Re: I need help with C(++)
Post by: on April 03, 2003, 06:10:56 PM
Quote

z5 wrote:
#include
#include
#include

void main(void)
  {
     const numberofstrings = 5;
     char str[numberofstrings][80],*p;
       
     for(p=str;p                {
                printf("Type string: ");
                gets(p);
                }
}


This won't work, even if you could force the assignment of p to the beginning of your array.  p is a char *.   p++ points to the char immediately following the char first pointed at by p.  To get p++ to skip 80 characters and point to the next string, you need to declare p as a pointer to an array of char[80] like this:

char (*p)[80];

I would never code it this way myself though.  To loop through arrays of strings I would use:

for (i = 0; i < numberofstrings; i++) {
   printf("Type string:  ");
   gets(str);
}

Since str is an array of character arrays, str
  • can be used as a pointer to a char, and this way the array notation takes care of the pointer arithemetic.


MikeS
Title: Re: I need help with C(++)
Post by: on April 03, 2003, 06:14:05 PM
Or better, use p = str[0];
Then in your loop, you'll need to use p+= 80.

--
MikeS
Title: Re: I need help with C(++)
Post by: Karlos on April 03, 2003, 09:12:18 PM
If it's a c++ project, you could just use the string class :-)
Title: Re: I need help with C(++)
Post by: Karlos on April 03, 2003, 09:27:29 PM
Title: Re: I need help with C(++)
Post by: Karlos on April 04, 2003, 09:47:31 AM
One last point,

It's generally not a good idea to declare arrays 'on the stack' like this.

You could make the array static, or allocate space with malloc (or new[] if using C++)

Also, my last example was a bit wrong in that you get the return character as the last char of your string. To fix this you get the number of chars read from fgets() and set the last character-1 to 0

eg
for (...)
{
   int len;
   printf("Type string: ");
   len = fgets(p->data, bufferSize-1, stdin);
   p->data[len-1] = '\0';
}
Title: Re: I need help with C(++)
Post by: Piru on April 04, 2003, 10:34:38 AM
@Karlos

Just being pedantic here, but:

a) If the stream end in immeditate EOF, your code trash memory *before* the buffer [0-1]. Not good.

b) The last char is not always a newline. If the stream ends (EOF) you now kill the last perfectly valid char. Not good.

Make it:

/* If the last char is a newline, kill it */
if (len && p->data[len-1] == '\n')
{
  p->data[len-1] = '\0';
}

/* Note to anyone who thinks the char could be '\r' too: PC stdio libs have automagic "\r\n" -> "\n" at input and automagic "\n" -> "\r\n" at output. Or at least should have. :-) */
Title: Re: I need help with C(++)
Post by: Karlos on April 04, 2003, 10:53:02 AM
@Piru

Thanks for that, you are completely correct. Everybody ignore me, I'm not fully awake :-)

I just posted without actually checking the behaviour of fgets() - I did edit my post just now but forgot to check since I'm at work mucking about with god awful vbscript (ewww!)

Anhow, listen to the guy, he knows what he's talking about!
Title: Re: I need help with C(++)
Post by: Karlos on April 04, 2003, 10:58:54 AM
Right, from the top :-D


#include
#include
#include

/* create a string buffer type */

const size_t bufferSize = 80;

typedef struct {
   char data[bufferSize];
} FixedStringBuffer;

void main(void)
{
   const size_t numberofstrings = 5;
   FixedStringBuffer strBuf[numberofstrings], *p;
       
   for(p=strBuf;p   {
      int len;
      printf("Type string: ");
      len = fgets(p->data, bufferSize-1, stdin);
      if (len && p->data[len-1] == '\n')
         p->data[len-1] = '\0';
   }
}

Title: Re: I need help with C(++)
Post by: z5 on April 04, 2003, 11:59:33 AM
my teacher will never believe that i coded this myself  :-D
Title: Re: I need help with C(++)
Post by: Karlos on April 04, 2003, 12:00:57 PM
It's got pointers, a structure and safety bound IO. What more does s/he want ?

:-)

-edit-

As long as you follow it, you can explain it if they get suspicious :-D
Title: Re: I need help with C(++)
Post by: z5 on April 05, 2003, 05:40:56 PM
ok, i've got another problem:

#include
#include

void main(void)
{
int aantalmaaltijden, jarenklant, prijsmaaltijd, prijsmaxmaaltijd, korting;
int kortingonderdrie, kortingbovendrie;
float totalebedrag;
char klant[80];

printf("Geef de prijs van 1 maatijd: ");
scanf("%d",&prijsmaaltijd);
printf("Geef de prijs van 5 maaltijden: ");
scanf("%d",&prijsmaxmaaltijd);
printf("Geef de korting bij minder dan 3 jaar klant: ");
scanf("%d",&kortingonderdrie);
printf("Geef de korting als 3 of meer jaar klant: ");
scanf("%d",&kortingbovendrie);
printf("Geef de naam van de klant: ");
gets(klant);
printf("Geef het aantal maaltijden: ");
scanf("%d",&aantalmaaltijden);
printf("Geef aantal jaren klant: ");
scanf("%d",&jarenklant);
}

Don't mind all the text (it's dutch). The problem is the gets(klant). If i run the program, the program doesn't wait for something to be typed on the keyboard and jumps straight to the next printf.

Any ideas?
Thanks
Title: Re: I need help with C(++)
Post by: Karlos on April 05, 2003, 05:43:58 PM
There's probalbly some newline chars or whatever left in the input buffer after scanf()

Try sticking fflush(stdin) before your gets() and see if that helps.

Title: Re: I need help with C(++)
Post by: z5 on April 05, 2003, 05:47:44 PM
bingo  :-o

You're my hero Karlos  :-D

Seriously though, you seem to know a lot about programming, yet reading some threads i have the impression that you don't do it for a living? Why not?
Title: Re: I need help with C(++)
Post by: Karlos on April 05, 2003, 05:55:13 PM
Another thing, if the user enters more than 80 chars for your gets() youre asking for trouble.

To limit the input to a max of 79 chars, use something like

int len;

fflush(stdin);
len = fgets(klant, 79, stdin);
if (len && klant[len-1] == '\n')
   klant[len-1] = '\0'; /* nuke the newline */


This is just the same as in te previous example with the FixedStringBuffer...
Title: Re: I need help with C(++)
Post by: Karlos on April 05, 2003, 06:01:39 PM
Quote

z5 wrote:
bingo  :-o

You're my hero Karlos  :-D




Aww, gee :-)



-edit-

Actually, you don't generally see this problem under AmigaOS because the interactive stdin/stdout generally flush automatically when changing from input to output and vice versa. This isn't true an all plafroms. However, fflush(stdin) won't hurt on platforms that don't require it so your code stays portable.

-edit-


Quote

Seriously though, you seem to know a lot about programming, yet reading some threads i have the impression that you don't do it for a living? Why not?


No more than many who frequent this place. I don't have much formal qualifications in software (I ado have a masters degree in chemistry though), but have been coding since I was six (ZX81!)..

I'd actually like to work in software development but the industry here in the UK isn't exactly crying out for programmers just now.

Hence the shift to web developemnt, which is having just as rough a time but with slightly better prospects. Just approaching the end of a six month  work-based intensive course in the latter.

My guess is that a web designer who is comfortable programming is slightly more sought after than either a programmer or pure web designer.
Title: Re: I need help with C(++)
Post by: Jose on April 05, 2003, 07:05:40 PM
"...I ado have a masters degree in chemistry though.."
I guess that industry is even worse!?
Seriously how come you take a masters and don't work in a related area :-?

It's just by curiousity, I'm finishing my degree and don't see much perspectives either (agronomy) :-D
Title: Re: I need help with C(++)
Post by: Karlos on April 05, 2003, 07:14:13 PM
I was following it with a PhD, but during that time the industry ended up in the crappest state ever. Every merger between the big chemical companies seemed to lose jobs rather than create them. The IT industry is suffering along the same vein currently.

To get a halfway decent job a PhD wansnt enough any more - I knew guys with post docs / industrial experience in the same job application queues as fresh PhD graduates.

Who would you give the job to?

-edit-

Also, I got scooped by the Japanese in my project, which didn't help :-)

So, having a good grasp of IT, I jumped ship. Right as the sodding .com bust happened!

So here I am :-(
Title: Re: I need help with C(++)
Post by: Jose on April 05, 2003, 07:53:03 PM
Maybe I should have started as a  construction worker some years ago. I have friends that earn more doing basic things in there  than some people with Masters, and they have plenty time to rumble and don't have many worrries  :-D
Title: Re: I need help with C(++)
Post by: z5 on April 14, 2003, 06:11:53 PM
Can anybody explain the following problem (it's driving me nuts) in C:

When i do 0.20 / 0.20 and put the the result in a float, i get 1.00 (which is great  :-) )

When i do the same and put the result in an integer, i get 0 (:-x). So i'm doing int = float / float

Same goes for:
 0.20/0.10 results in 2 when i put it in a float
 0.20/0.10 results in 1 when i put the result in an integer??
Title: Re: I need help with C(++)
Post by: Kronos on April 14, 2003, 06:15:05 PM
Because that is just how it is .......

Must have something to do how and when data is tranformed
from float to int. Better learn to live with it.
Title: Re: I need help with C(++)
Post by: Karlos on April 14, 2003, 06:19:36 PM
Sounds like truncation error.

Try an explicit cast, eg

float a, b;
int x;
...
x = (int)(a/b);

Or, you could write a round() function that does

int round(float x)
{
   if (x>0.0) return (x+0.5);
   if (x<0.0) return (x-0.5);
   return 0;
}
Title: Re: I need help with C(++)
Post by: z5 on April 14, 2003, 06:28:00 PM
The cast doesn''t work.

Is there a function in c where i can drop everything behind the comma,
eg
float 5.20 => 5 but there must be no rounding up.?
Title: Re: I need help with C(++)
Post by: PiR on April 14, 2003, 07:32:38 PM
Hi

The explanation is quite simple:
Due to the roundings done in floating point calculations 0.2 / 0.2 is not really 1.0, but 0.9999....
As you see the default rounding method of your compiler is 'towards zero', in other words 'cut off everything after dot', so you got your 0 integer.

I think I could give you one more warning.
Because of the nature of relation between binary and decimal, it is not even possible to represent numbers, like 0.2 in float preciselly. If you checked it more carrefully you can find you they are ROUNDED to the nearest representablefloat, that is somewhat like 0.2000(...)2.

If being precise is 'a must' for you (things like indexing arrays), using floating points is not the best idea. You should remember that these representation is always treated as 'the value nearby X'.

Good luck
Title: Re: I need help with C(++)
Post by: Karlos on April 14, 2003, 08:42:22 PM
Quote

z5 wrote:
The cast doesn''t work.

Is there a function in c where i can drop everything behind the comma,
eg
float 5.20 => 5 but there must be no rounding up.?


In math.h I think there are floor() and ceil() functions that do what your'e looking for.

As I recall,

double floor(double x)

Returns the largest integer value (expressedl as a double) not greater than x

double ceil(double x)

Returns the largest integer (expressed as a double) not less than x

ie

floor(-3.5) => -4.0
floor(3.5) => 3.0
floor(-2.0) => -2.0
floor(2.0) => 2.0

ceil(-3.5) => -3.0
ceil(3.5) => 4.0
ceil(-2.0) => -2.0
ceil(2.0) => 2.0


Hope this helps
Title: Re: I need help with C(++)
Post by: iamaboringperson on April 15, 2003, 01:18:35 AM
this should be under 'AmigaOS development'