jephthah 1,888 Posting Maven

remove <iostream>
remove <cstdlib> ... replace with <stdlib.h>
remove "using namespace"

calling a function "print" is bad practice.

void print(int x)
should not also have a local redeclaration of "int x" choose either one or the other. what is this doing, anyhow? printing 1-10? why do you need a dedicated function to do that?


good lord this is a mess.

where does your main() routine even end? where do your function definitions begin? are your functions "printtable" and "print" the same functions?

clean up this mess of code and repost it using proper indentations and code tags, so we can see what the heck is going on.

this is unreadable.

jephthah 1,888 Posting Maven

EDIT : oops, i didnt realize this this thread was 5 days old.

nothing wrong with 70%.... heavy reads in a while loop,that would be expected. if other programs need (or are already using) cpu resources while this program is running, they will share the available resources.

and yes, get rid of the bzero. it's unnecessary. the fgets will null terminate the buffer after each read.


.

jephthah 1,888 Posting Maven

Why these lines?

#include <iostream>
using namespace std;

because he thinks this is the C++ forum.

jephthah 1,888 Posting Maven

it takes user input (from keyboard) by using stdin, like so:

char inputStr[MAX_STR_LEN];
fgets(inputStr, sizeof(inputStr)-1), stdin);

... is this what youre asking?

if you want to take input via a file, then check out the example given for fgets()

jephthah 1,888 Posting Maven

it's cool. let us know if that doesn't fix your problem.

jephthah 1,888 Posting Maven

hi, welcome!

you'll find a lot of great help in teh Java and C forums. cant say i know anything about prolog, tho ;)

jephthah 1,888 Posting Maven

because your first arguments to fgets are all single characters.

the argument is supposed to be a STRING. not a single character. a single character is actually an 8-bit integer, so it thinks you are passing in an integer when it expects the starting position of a string (aka character array).

define your character arrays (ie, strings) thusly:

char str1[32];
char str2[99];
char str3[MAX_STR_LEN];

//etc.

or whatever size you need.

and PLEASE use code tags next time. look at your code in the first post. is that even readable to you? its not to me.

jephthah 1,888 Posting Maven

i can see your point. there's value to keeping it simple. and often i won't bother trying to correct the use of scanf(), when the issue being addressed is unrelated.

but in this case, i disagree, because the very problem is due to scanf(). it doesnt take Miss Piggy to come along and fatfinger a user entry all to hell. So your getchar() is just putting lipstick on a pig. And then walking that pig to a synagogue on Yom Kippur. While munching on a bag of pork rinds.

wait, what?

okay, never mind. i'll agree to disagree, and leave your scanf()s alone from now on.

.

jephthah 1,888 Posting Maven

Add this right after your scanf()'s:

getchar();

this is wrong. its sloppy and it barely addresses the problem. in practice, with more complex inputs, it will fail more often than it works.

if the user enters a number followed by enter, like this: "12\n" , adak's suggestion will work

but if the user input diverges from that in the slightest (and it will) ... if they enter other stuff after the number (a "\tab" or a space " " or some other input), like this: "12 \n" ... it will still fail to work correctly.

do not use scanf. use fgets to a string, then convert the string to an integer, long, float or double using "atoi" "atol" "atof" or "atod"... even better are the functions "strtol" and "strtod"

.

jephthah 1,888 Posting Maven

the quick answer is that youve got unbuffered input due to your use of scanf()

but you've got a number of bad programming practices here, that i can't ignore. I suspect the blame is due to incompetent instructors teaching substandard curriculum on compilers that are 15 years out-of-date.

So I'm just going to lay it out, and if you choose not to take this advice ... well, at least I told you.

the non-standard <conio.h> library is obsolete. cease using it. this means that you will not be able to use things like "textcolor" which is unnecessary now that the days of DOS has been over for at least 10 years, and "clrscr" which is always obnoxious. you will not be able to use "getch" either, but don't worry the standard-C library <stdio.h> has "getchar" which will suffice. But you'll really want to use "fgets" anyhow, for most console input.

do not use "exit()" to quit a program due to normal events. this is a terrible practice, and will cause all sorts of problems once you start writing real programs that interface with real hardware and live databases.

steer away from using scanf(). the lure is tempting, but you need to learn to avoid it. its the source of many problems. fgets() will get a string safely that can be converted to numeric value and allows a relatively easy error-checking method to ensure the input buffer is cleared in case input is too long. (i'm …

urbangeek commented: Awsome...thanks!! +0
jephthah 1,888 Posting Maven

[EDITED]

nevermind. lets not go there. daniweb is a such a nice site.


.

jephthah 1,888 Posting Maven

Nick, you know i love you, man

:P


.

jephthah 1,888 Posting Maven

if there's a thread that needs bumping, it's this one.

Keep Hope Alive!

Nick Evan commented: So you gave negrep because I deleted "me toos +0
jephthah 1,888 Posting Maven

I'm making a program that will attempt to lessen the effects of a flash drive when placed in an infected pc.

Basically it will make a folder named autorun.inf
then make a folder named "con" inside it...

oh, look, another skript kiddie trying to write a piece of malware.

i know you think you're clever, but this trick is like 15 years old, and won't crash computers with OS'es from the 21st Century.


.

jephthah 1,888 Posting Maven

^ you mean you're a junior, as in a third-year undergraduate?


.

jephthah 1,888 Posting Maven

@jephthah, thanks alot :)
but there is no such thing in my lesson how to give multiple values for IF

well, you were certainly trying to do so! but you were doing it wrong. IF takes one conditional statement. the statement may have one or more values. you need to be able to deal with ANDs and ORs in your conditional statement, as you can see by your need to find the condition when 'a' equals either 0 or 1. to try and do this with only one value at a time, would be ridiculous

@WaltP , Our teacher teaching us from the basic and they told us to use such functions, i don't know any other function to use then these void main(void) and clrscr () & getch () , can you tell me which functions should i use istead of the functions above ?

i wasn't going to bother correcting this, since you've got more fundamental problems... but since Walt brought it up:

(1) always use int main (void) ... you will need to add a return 0; at the end of your main block. "void main" is wrong. it's undefined and can cause all sorts of problems in larger projects. any instructor that tells his student to do so, is immediately suspect of incompetence.

(2) you should never use "clrscr()". it's entirely unnecessary and obnoxious.

(3) use getchar() instead of getch().

(4) stop using the conio.h library altogether. use stdio.h and stdlib.h …

jephthah 1,888 Posting Maven

line 7 is the problem.

a=0 is an assignment. a==0 is a conditional statement. you need to understand the difference. also, you can't test multiple conditions by throwing a comma between values. you need to fully express each condition, separated by an AND (&&) or an OR (||) as the logic you're trying to acheive requires.

so, what you are trying to say in line 7 should be if (a == 0 || a == 1) this is fundamental stuff. you need to review your early lessons on IF statements, conditional and assignment operators.

jephthah 1,888 Posting Maven

i may be (re)stating the obvious, but just for clarity's sake:

what Banfa meant, i think, is that you will need to take the references to the prototypes out of the C file and leave them only in the header file. in the C file(s), you will have the single line #include "myheaderfile.h" or whatever you call it.

the other programs will link the library when they are built. Depending on how the library is built, those programs' C files that use the library's external functions will probably need to have that #include "myheaderfile.h" line, as well.

and you may already know all this.

.

jephthah 1,888 Posting Maven

this is the reason why globals are generally considered bad programming. unless you have a compelling reason to do so, do not use global variables.

pass your array as a pointer argument into the functions that will be making use of it and/or modifying it.

your problems will disappear.

jephthah 1,888 Posting Maven

yeah, pretty much ... the rest is just details :P

just to be clear, you write the code and the header file, then you compile and build it as a library file, rather than a binary executable. the resulting library file(s) along with the .h file are distributed.

Note for MS Windows .DLLs, you have to specify in the code which functions will be externally visible. And Linux has completely different methods to create and include shared libraries. See the link above.

it's some extra work, but the benefit of doing it this way, rather than just handing them the .C source code, is that libraries can be maintained/revised without affecting the programs that use them (unless the prototypes are changed) also the library build is controlled and can't be modified in a way not intended by the author, other than allowing them to tweak #define values in the header


.

jephthah 1,888 Posting Maven

header files are good programming practice especially for large projects with mulitple files.

but, no, you can't just plop a header file into some other program and have it work without code available. you do need to have the source code -- in one form or another -- included as well as the header.

in many cases, such as standard libraries like <stdio.h>, the source code is part of a library that is included in the build when the header file is included. these libraries are the source code, and are already compiled for your specific operating system, and are typically provided as .lib or .dll files

so for your code to be portable, you would have to distribute the source code, either as the .c source file or in an external library, if you want to allow that functionality to be ported to some other program. merely including the header prototypes will not do it.

but it is good practice to put all the prototypes and defines and global declarations and typedefs and etcetera in their own header files. as your projects get bigger, these header files can and will become fairly substantial, and it becomes necessary to maintain programmer sanity to keep everything organized.

also it's important to not redefine elements, so the header files are framed with their own define to keep them from being called more than once.

/**********************************
*  myproject.h
*
*  contains definitions and prototypes
*  for myproject.c …
jephthah 1,888 Posting Maven

Microsoft's Visual C and GCC are both pretty sweet for doing small assignments and programs. I use them a great deal, as does the rest of the First World, whereas nobody in technically competent companies or institutions here in this 21st century use Turbo C.

seriously throw that archaic Turbo C crap away. let it die like it should have already done back in the early 1990's.

jephthah 1,888 Posting Maven

scanf is often the source of input problems. as you can see, you have the most trivial example and it's already being problematic. since there are better alternatives readily available, you'll do well to learn to stop using it as soon as possible.

i too am partial to fgets(). it's intuitive to use and safe. the sooner you start using it, the sooner you will learn to love it.

word of caution: never, ever, use the similar-looking "gets()" function, however. "gets()" is an idiot test. anyone who ever suggests that you use it is an idiot. this especially includes programming instructors. here is why.

jephthah 1,888 Posting Maven

jesus, man, you don't need to post all 156 identical errors. :confused: in fact you really don't need to post any. because the answer is simple:

rule #1 -- you can not take header files from one compiler's library and plop them into another. this will not work.

"graphics.h" (and "conio.h", too) is non-standard Borland/Turbo trash. and as such, Microsoft's Visual C compiler does not, can not, and will not use it. the sooner you cut your losses and forget all this non-standard crap you learn using Turbo C, the better.

however, if you are being forced to use Turbo C and its obsolete, archaic libraries by your incompetent university's administration, then you better get off MSVC now and go back to using your 1980's era toy computer, and spend your time there to figure out what you're doing wrong.

when you're ready to join the 21st century western world, you'll toss all that Turbo C code away.

.

jephthah 1,888 Posting Maven

you probably want to look into sparse matrix compression algorithms

jephthah 1,888 Posting Maven

i know the range of int, it will not find the factorial of 8 or number above 8 because this would be outside the int range....

the size of "int" is determined by the compiler.

if you are using a relatively modern compiler, as in from the past 15 years or so, the size of "int" should be 32 bits.

this will allow factorials up to !12

and if you use a type "long long", this will be 64 bits, and i believe will allow factorials up to !20

jephthah 1,888 Posting Maven

okay, sorry, you're right i'm not understanding your question. let me try again.

you're trying to calculate a factorial. in this example you're trying to calculate the factorial of "5". the factorial of 5 is

5! = 1 x 2 x 3 x 4 x 5 = 120.

your program performs this by a using a loop, by multiplying each of these numbers and holding the value in the variable "c". in your specific case, your program does it in reverse

5! = 5 x 4 x 3 x 2 x 1 = 120.

but its the same thing. in any event, please forget that i said anything about addition. you should not be using the addition operator "+" or "+=" for anything here.

here is what you have:

a = the number you want to take factorial of
b = a loop counter
c = the total answer, kept as a running value.

c is initialized to 1
c = 1

a is set to 5
a = 5

b is set to value of a, at the beginning of the "for" loop.
b = a

start loop using b, and decrement by 1 as long as b > 0

first loop:
b = 5
c = c * b
c = 1 * 5
c = 5

second loop:
b = 4
c = …

jephthah 1,888 Posting Maven

okay, hang on a sec. lets get the definition of 'factorial' agreed upon.

factorial is a total products, as calculated using recursive multiplication from 1 up to the number that you are getting the factorial of.

factorial of 5, is written as "5!"

and 5! = 1 x 2 x 3 x 4 x 5 = 120.

so you should be multiplying it as originally shown, using the "c *= b" assignment

(there is another operation that does addition, like 1 + 2 + 3 + 4 + 5 = 15, but that's not a factorial, i forget what it is called.)

so the whole point of this program is to be able to vary the number you want to compute the factorial of. in your example 5 is used, but there you should be able to check any number within a reasonable range, such as 6! or 7!, etc....

that's why you use a loop, because the point is not to just hard-code "1x2x3x4x5" ... but to be able to count any number of factorials from 1! through at least 12! depending on how large of an integer you can handle.

jephthah 1,888 Posting Maven

and why we've used c in a program ?? can't we done this without using airthmaetic assignment operator ?

not sure i understand your question. factorial is recursive multiplication, so you have to do some amount of arithmetic, and you have to assign the value to something, right?

if you want to get rid of a variable, you could get rid of "c" i suppose, and keep the total factorial product in "a". you'd save a variable, and maybe a line of code or two, but the end result should be the same.


.

jephthah 1,888 Posting Maven

thanks alot :)
but here b is equal to 5 4 3 2 1 , then why ithis program is multiplying all the values of b ???
i mean why the ouput is 120 since we never said to the program to multiply all the values of loop

i don't know why you're multiplying it. you're the one who wrote the program, right? ;)

change the multiplication operator to an addition operator if you want to recursively add values c += b .

jephthah 1,888 Posting Maven

because your assignment statement c *= b; is a shorthand way of saying c = c * b by setting c=1, this correctly causes the first execution to be read as "c = 1 * b", and uses the value of c recursively each time afterward.

if you don't initialize c=1 at the very beginning, the first execution will be "c = <some_unknown_value> * b"... and you don't want that.

.

Xufyan commented: thankx alot +1
jephthah 1,888 Posting Maven

Funny thing, Walt, i've noticed your own recent posts where you do exactly the same thing.

such as this one here, where your only response to some guy's crap code was to tell him that it's full of problems and he needs to refrain from posting.

Please ignore yila's code. It is full of problems.

yila, please refrain from posting (supposedly) working code for people. They learn nothing so you are hurting more than helping. Especially when you use bad coding practices.

C Forum "Half Pyramid" thread post #8, March 07 2010

No explanation of why it was bad. Not even an explanation of *what* was wrong.

Now I wouldn't ever call you out on it because i totally agree with you. I'm tired of explaining the same things over and over to every noob and his brother. Crap code is crap code, and being nice and patient about it doesn't change the fact that most of them aren't listening anyhow except long enough to get the quickest and easiest answer.

And as for credibility ... that's a non issue. Veteran posters like yourself with thousands of posts and hundreds of "solved threads" don't NEED to establish credibility. At least not for newbie posters asking basic "why doesn't my program work?????" questions.


.

WaltP commented: they do to newbies. Veterans are still unknowns. +11
Aia commented: I like the part about..."every noob and his brother". And how about a couple posts above that one? +8
jephthah 1,888 Posting Maven

re: allocating your array

matrix = (int *) malloc(nrows * sizeof(int));
if(matrix == (int *) NULL)

what is your "nrows"?? its uninitialized. you need to specify what the size of the array you want to malloc.

note, the size of a single int is either 4 or 8 bytes depending on your compiler. but don't worry about that, what you need to worry about is malloc-ing enough ints to account for the number of rows AND the length of each row.

so not only will you need "nrows" to be the correct value, but you need the size of each row... think "ncols" or "rowlength"

a couple points while im here...

don't cast your malloc as an (int *) that's unnecessary and potentially buggy. it dates from the days before ANSI C and is not good practice.

and dont cast NULL as an (int *) either. NULL is already defined just fine, in the standard library.

as for "nrows" this is the number of rows that you should have already read from your text file before you allocate your matrix. which you havent

so make a while block that continues to get one line at a time as long as the result is not null. use "fgets"

see: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

consider this example:

char singleLine[MAXLINELEN];
nrows = 0;

while (fgets(singleLine, MAXLINELEN-1, infile) != NULL)
{
    nrows++;
    printf(line #%d: %s\n",nrows,singleLine);
}

how can you apply it to your code? …

jephthah 1,888 Posting Maven

okay, that's a start. what's your question?

jephthah 1,888 Posting Maven

so what's your question? and what have you done so far?

go ahead and show us what you've got. here's a handy template:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{

   // paste code here

   return 0;
}

oh, wait? you want hints on how to start? okay, here are the basic functions, in roughly the order you'll want to use them. give or take...

malloc
fopen
while
fgets
if / else
realloc
fclose
free

there's probably a few more, but don't say i didn't give you anything.


.

jephthah 1,888 Posting Maven

i shall post in here now, so i can remember to visit it later, when i am "leisurely bored" :)

jephthah 1,888 Posting Maven

Well, this was probably a bad idea,

yeah.... it's unfair to the newbie poster to be handed such a lovingly polished solution, and it's unfair to the rest of us here who strive to teach students how to do their own work without handing it to them.

it'd be one thing if he were a professional trying to solve a difficult problem. but the rule here is "We Don't Do Your Homework". it's kind of hidden up at the top of every forum as a sticky.


but, i will say, your code is very nice.

.

jephthah 1,888 Posting Maven

i'm still saying that overwriting the original string with \newline characters is a bad idea. it makes the program unnecessarily complicated, and opens up more opportunities for buggy code.

I suggest that you reconsider your approach to the problem. to put it one way, i think you are "going around your ass to get to your elbow". nothing personal, its a problem all new programmers (and some old) have.

consider this: simply break your string into tokens that are already delimited by the existing spaces. then, concatenate all IP addresses (with or without their trailing commas) into one string.

const char str = "/usr/bin/ssh * 147.188.195.15, 147.188.193.15, 147.188.193.16 22";

char PathName[MAXPATHSIZE] = '\0';
char UID[MAXUIDSIZE] = '\0';
char IPaddr[MAXIPADDRSIZE] = '\0';
char Port[MAXPORTSIZE] = '\0';

char *ptr;

ptr = strtok(str," ");
while (ptr != NULL)
{
   if (strstr( ptr, "/") != 0)
      strcpy (PathName, ptr);
   else if (strstr( ptr, ".") != 0)
      strcat (IPaddr, ptr);
   else if (strstr( ptr, "*") != 0)
      strcpy (UID, ptr);

   /*
   ...  now you figure out how to distinguish between numeric UIDs 
   ...  and numeric Port Numbers
   ...  One possibility is a "state machine" or just a flag that tracks when 
   ...  the IPaddresses have been found, so a subsequent
   ...  simple numeric must be a Port and not a UID.
   ...*/

   ptr = strtok(NULL, " ");
}

.

jephthah 1,888 Posting Maven

Hello, I'm trying to split a string into 4 separate strings using a delimiter "\n"

i would suggest that replacing printable characters with '\n' as a delimiter is a Bad Idea. Because what is '\n', anyhow?

is it 0x0D ?
is it 0x0A ?
or is it 0x0D + 0x0A ?

rethink the problem and just parse your tokens on what actually exists without overwriting. if you must overwrite, then at least use another printable character.


.

jephthah 1,888 Posting Maven

man, when i was in the Navy, we had our BMI regularly measured. it used some other measurements like neck and waist but essentially the same.

there was a guy who had a BMI of 8 or 9. many of us had BMIs of 15 or so.

the criteria that <18 is underweight and <15 is starving is bullshit. they've changed the standards to match the average american fatbody .

jephthah 1,888 Posting Maven

if you want the capability of being able to shoot yourself in the foot, you can try

3. use fixed width records and one or more of "fseek", "ftell", "fsetpos", and "rewind" to manipulate the filestream and edit it in-line.


personally, though, i would go with either one of Narue's #1 or #2. manipulating inline can be fun, but ultimately is just asking for trouble.

.

jephthah 1,888 Posting Maven

i don't really know what you're talking about, but thanks for posting your solution.

someone will wander across this someday and be helped by it.

:)

jephthah 1,888 Posting Maven

you need to post a question if you want an answer.

jephthah 1,888 Posting Maven

when you 'getch' you're taking the next character off of the input queue for processing.

this assumes once you've processed it, you're done with it, and will (probably) eventually want to get another character off the input queue.

'ungetch' puts that input back on the input queue.

this effectively allows you to "peek" at the input queue and know what the next character is without destroying it, so that it can be used again at some other point.

jephthah 1,888 Posting Maven

the main() program can often be called by a parent program. 'return 0;' indicates to the caller (parent) that the main() program executed correctly.

so... generally speaking, the main function must be of type 'int' and therefore must return some integer value on completion. zero (0) is the standard "successful" return value (think: returned with zero errors) although it could be some other value that indicates an error state, depending on the caller

if main does not return a value (like the case of 'void main()' ) then you are now in the realm of "undefined behavior" when the program is called by another. Undefined behavior is almost always a Bad Thing.

.

no1zson commented: great explanation +3
Salem commented: Hell yeah - I had to deal with a "void mainer's" prog once, the exit status was even worse than rand() +36
jephthah 1,888 Posting Maven

the error is probably due to the fact that 'x' isn't initialized, so it's value is something like negative eleventy thousand, causing your program to crap the bed when it uses it as one of the array indices.

jephthah 1,888 Posting Maven

you got both loops fighting over the same index 'i'

jephthah 1,888 Posting Maven

Better add someone else to the reading list

this thread is a disaster. :)

you are a patient man, Salem.


.

jephthah 1,888 Posting Maven

use code tags correctly. and make sure your code is indented. otherwise, it's a ridiculous mess, and no one will want to look at it.

int main(void)
{
    // hello, i am properly formatted C code.
    // aren't i nice?

    if (your_code == properly_formatted)
    {
        youWillGetResponse = TRUE;
    }
    else 
    {
        youWillGetResponse = NULL;
    }

    return toBeginning(andTryAgain);
}
tux4life commented: Heh, nice code :P +15
jephthah 1,888 Posting Maven

:$