Narue 5,707 Bad Cop Team Colleague

Can anyone explain -in simple words as possible- what happens in the first code so that it prints the result that way?

Undefined behavior.

Narue 5,707 Bad Cop Team Colleague

you can talk to him if u want for this.

Invite him to Daniweb and I'll be happy to tear him a new one.

Narue 5,707 Bad Cop Team Colleague
#include <cstdlib> // I'm needed for rand() and srand()
#include <ctime>   // I'm needed for time()
#include <iostream>

int main()
{
    // Put me at the start of the program
    srand((unsigned)time(0));
    
    const int N = 100;
    
    // Watch as random numbers between 0 and N are generated
    for (int i = 0; i < 10; i++)
        std::cout << rand() % N << '\n';
}
Narue 5,707 Bad Cop Team Colleague

graphics.h is certainly a problem, why do you use a graphics library from two decades ago?

Narue 5,707 Bad Cop Team Colleague

the job offered do not focus mainly about c++

It doesn't have to focus mainly on C++. If getting the job depends on answering a question, you don't deserve to get the job if you can't answer the question. This is simple common sense.

NathanOliver commented: amen to that +10
Narue 5,707 Bad Cop Team Colleague

my friend need it for him to land a job..

If your "friend" can't answer the question without help, he shouldn't get the job. Also note that confusing both parentheses and braces for angle brackets is a sure way to not get hired for any job that requires even the most rudimentary knowledge of C++.

Narue 5,707 Bad Cop Team Colleague

Given that at least Ideone has an API, that's not an unreasonable suggestion. Though many (if not most) code blocks on Daniweb are not meant to be compilable as-is, so the best fit for such a feature would be in our code snippets rather than discussion threads.

Narue 5,707 Bad Cop Team Colleague
pStu= new (nothrow) student pStu[i];

Should be this:

pStu= new (nothrow) student[i];

You also need to include <cstdlib> because that's where system() is declared.

Narue 5,707 Bad Cop Team Colleague

I am getting a hex values as my output and i want to convert it into ascii so that it is readable.. does this help you?

No, it doesn't. Your terminology is confused, which makes it very difficult to understand exactly what you want without specific examples. Please post the exact output you want to see, since you're clearly not describing the problem adequately.

Narue 5,707 Bad Cop Team Colleague

Shouldn't the strlen only return 2 (or 4 with 'ls'), shouln't the string in the system(); call be cut of, and shouln't I get a segmentation fault?

Yes, yes, and yes. Or no, no, and no. Or any combination thereof. Undefined behavior means any damn thing can happen, which includes working perfectly.

Narue 5,707 Bad Cop Team Colleague

Only one problem, what is a masked text box?

Here's a hint for the future: always try to research things like this on your own first. The only if you come up with nothing or fail to understand what you've found should you ask for clarification. In this case, "masked text box" is standard terminology, and when passed to Google will certainly tell you what you want to know in the first hits.

Narue 5,707 Bad Cop Team Colleague

Still, is such an concept all that useless?

Yes. If you want GUI behavior, write a GUI. Forcing the console to act like a GUI is awkward and confusing to users.

Narue 5,707 Bad Cop Team Colleague

But does that mean such a automatic aligning of the matrix in CONSOLE Application is impossible, No other robust method?

No, it just means I had neither the time nor the inclination to write a robust function for you when I think the whole concept is stupid. raw_gets() is a good starting point for adding the necessary checks and features to make it robust, but I'll leave that up to you.

Narue 5,707 Bad Cop Team Colleague

tell me this... is the following code correct?

#include <iostream>
using namespace std;

int main () {
  int n;
  n=48:45:4c:4c:4f:20:57:4f:52:4c:44;
  cout << "ASC " << n << endl 
  return 0;
}

Is this a trick question? Of course it's not correct, as any compiler will tell you. How about explaining exactly what output you were expecting from this code, and I'll tell you how to achieve it correctly.

Narue 5,707 Bad Cop Team Colleague

Wow! I never knew it was a C function. Thanks for sharing that, now onward i will not use that.

The fact that it's a function inherited from C is largely irrelevant. The important piece of information is that gets() is quite literally impossible to use safely. There's always a chance of buffer overflow, and you cannot avoid it. You can create the same problem using cin and C-style strings:

char buf[N];

cin >> buf; // No better than gets()

But at least here there's a fix for it:

char buf[N];

cin >> setw(N) >> buf; // All better

Of course, in C++ you should prefer to use the string class over C-style strings because they're easier to get right.

Narue 5,707 Bad Cop Team Colleague

Please provide some new information to justify a second thread on the topic.

Narue 5,707 Bad Cop Team Colleague

But why did you ask me to use at my risk?

Because it's example code and not robust enough to be usable in any kind of real program.

Narue 5,707 Bad Cop Team Colleague

I understand your confusion, but please don't be tricked into thinking that the code isn't broken when you provide insufficient space for strcat().

Narue 5,707 Bad Cop Team Colleague

The question is binary in the majority of cases: you either have a degree or you don't. Your GPA and grades in the process of obtaining a degree are largely irrelevant after graduation.

Narue 5,707 Bad Cop Team Colleague

Can anyone explain to me in details preferable with an example the different between i++ and i++ please.

The standalone difference is as functionally as follows:

// A function that performs ++i
int prefix_increment(int& i)
{
    i = i + 1;

    return i;
}

// A function that performs i++
int postfix_increment(int& i)
{
    int temp = i;

    i = i + 1;

    return temp;
}
Narue 5,707 Bad Cop Team Colleague

I compiled it on Dev C++ and that is exactly the output i got. Please tell me what is wrong about it?

It doesn't matter what result your compiler gives you. Allow me to summarize since you're reading-impaired (ie. the following has been said multiple times already in this thread): The behavior is undefined, and thus, completely unpredictable. Your mistake is assuming that test results from Dev-C++ will be consistent on all other compilers, which is wrong.

Narue 5,707 Bad Cop Team Colleague
*p ^= *q ^= *p ^= *q;

This statement invokes undefined behavior by modifying an object multiple times between sequence points. While cute, the correct form of an XOR swap is as follows:

*p ^= *q;
*q ^= *p;
*p ^= *q;

Notice how it's broken down into separate statements; the end of a statement introduces a sequence point. You can also use the comma operator if you want to be clever, but it's not recommended for readability purposes:

*p ^= *q, *q ^= *p, *p ^= *q;
Narue 5,707 Bad Cop Team Colleague

Your program only needs to print out the sequence?

Narue 5,707 Bad Cop Team Colleague

you should get 7 6 6
and its simply bcoz printf has the precedence from Right to Left.

Did you not read the thread before posting your incorrect answer?

Narue 5,707 Bad Cop Team Colleague

as far as I can tell, strcat depends on the string pointed to by its first parameter to be large enough to hold the two strings.

Correct, it's your job to ensure that the destination has enough room.

but if I change the code to buff = malloc(sizeof(command)+2); (or pretty much any size at all, smaller than 42) the 'string' is expanded to be 42 characters long?

Expanded? No. C doesn't stop you from writing beyond the boundaries of an array. In Java, for example, you'll get an exception immediately, but C will happily write to memory you don't own and silently corrupt things. If you're lucky, you'll corrupt something that causes a fatal error, but in this case it seems as if you weren't lucky.

Narue 5,707 Bad Cop Team Colleague

Obviously I have some wrong assumptions, because this prints "strsize = 8" no matter what.

Good call. buff is a pointer to char, so sizeof(buff) will always tell you what the size of a pointer to char is, not the length of the string it points to (if it points to a string at all, which isn't a safe assumption). What you want is the strlen() function, not sizeof.

Also note that strcat() expects the destination to be a valid string, which means you code is broken. This will fix it:

char* buff = malloc(sizeof(command)+42);

buff[0] = '\0'; /* Make buff a valid string */

strcat(buff, "notify-send \"notif finished\" \"Command: '");

Finally, it's good practice to check malloc() for failure. Otherwise you'll attempt to dereference a null pointer.

Bladtman242 commented: Solved my (initial) problem :) +3
Narue 5,707 Bad Cop Team Colleague

getcwd() returns the current working directory. That's the directory to which you can expect relative paths to resolve. Thus, it certainly explains why your relative path isn't finding the file if the current working directory is different. An easy solution would be using chdir() to force the current directory you want rather than using whatever happens to be the default.

Narue 5,707 Bad Cop Team Colleague

Your compiler should support some form of getcwd(), check the documentation.

Narue 5,707 Bad Cop Team Colleague

yes

Then post a complete test program so we're not forced to read your mind for necessary details.

Narue 5,707 Bad Cop Team Colleague

Is your array sorted?

Narue 5,707 Bad Cop Team Colleague

Since it is a pointer, what you are doing is printing the address of the pointer, not the contents.

Pointers are confusing for many people, so you should be especially precise with your phrasing. The address of a pointer is not the same as the address stored by a pointer. The contents of a pointer is the address stored.

The question was why is the address stored by a pointer to member not equivalent to the expected format of a memory address when printed. And the answer was a pointer to member does not store a memory address, it stores sufficient information to provide an offset into the target class when applied to an object of that class.

Try "cout << *ptr << endl;" instead.

Note that the discussion is about pointers to members, not regular pointers. They're most certainly not the same thing, hence the wildly different (and awkward, in my opinion) syntax.

Narue 5,707 Bad Cop Team Colleague

Isn't it should be pointing the address of variable p?

You can't expect a pointer to member to be printable at all, actually. The term "address" is used to mean "reference to a location", which for practical reasons compilers have implemented as a physical or virtual memory address. However, that's not required at all even for regular pointers. Pointers to members are especially confusing because they're still an "address", but a simple pointer can't be used due to the potentially complex nature of the class structure.

Usually some form of thunk is used instead as an offset into the class.

Narue 5,707 Bad Cop Team Colleague

Well it is undefined in gcc compiler.

It's undefined in the C language specification. Compilers can do anything they damn well please when it comes to undefined behavior.

...but in Dev C++ or Turbo C++

It's still undefined. Just because you can pick out the method used in a specific compiler doesn't make the code any less broken.

Narue 5,707 Bad Cop Team Colleague

in the end of each program, i get the message "Process returned 0 (0x0). execution time : ....... press any key to continue"
How can i get rid of that.

Stop running the program from within Code::Blocks. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

If your program uses the .NET framework then obviously that's a dependency required on the target machine.

Narue 5,707 Bad Cop Team Colleague

AES isn't especially difficult to implement from the specification. Ignoring the usual caveats of reinventing the wheel on important stuff like encryption, you could write your own class:

#ifndef JSW_AES_PROVIDER_H
#define JSW_AES_PROVIDER_H

#include <vector>

namespace jsw {
    namespace encryption {
        typedef std::vector<unsigned char> bytes_t;
        
        class aes_provider {
        public:
            aes_provider(bytes_t key) { reset(key); }

            void normalize(bytes_t& bytes);
            bytes_t encrypt(const bytes_t& bytes);
            bytes_t decrypt(const bytes_t& bytes);
        private:
            static bytes_t::value_type Sbox[][16];
            static bytes_t::value_type Sbox_inverse[][16];
            static bytes_t::value_type Rcon[][4];
        private:
            int Nb; // Input block length in 32-bit increments (always 4)
            int Nk; // Key length in 32-bit increments (4, 6, or 8)
            int Nr; // Number of rounds corresponding to key size (4:10, 6:12, 8:14)

            bytes_t key;                // Seed key
            std::vector<bytes_t> w;     // Key schedule
            std::vector<bytes_t> state; // State matrix

            void reset(bytes_t key);
            void key_expansion();
            void add_round_key(int round);
            void sub_bytes(bytes_t::value_type Sbox[][16]);
            void shift_rows();
            void inverse_shift_rows();
            void mix_columns();
            void inverse_mix_columns();
            bytes_t sub_word(bytes_t word);
            bytes_t rot_word(bytes_t word);
            unsigned char gfield_mul(unsigned char a, unsigned char b);
        };
    }
}

#endif
#include <stdexcept>
#include <vector>
#include "aes_provider.h"

namespace jsw {
    namespace encryption {
        void aes_provider::normalize(bytes_t& bytes)
        {
            // Add null padding to the input (modulo 128-bits for AES)
            while (bytes.size() % 16 != 0)
                bytes.push_back(0);
        }
        
        bytes_t aes_provider::encrypt(const bytes_t& bytes)
        {
            state = std::vector<bytes_t>(4, bytes_t(Nb));

            // Input to state
            for (int r = 0; r < 4; r++) {
                for (int c = 0; c < Nb; c++)
                    state[r][c] = bytes[r + 4 * c];
            }

            add_round_key(0);

            for (int round = 1; round < Nr; round++) …
Narue 5,707 Bad Cop Team Colleague

I know that with the pointer you use the "->" operator to access the object methods, and with the other one you use the "." operator, but what exactly is the difference between them?

In the first declaration, rectangle is a reference to an address where a Shape object happens to be stored. rectangle is not a Shape, it's a container for an address that will be interpreted as a Shape object. This differs from the second declaration where rectangle is a Shape object.

I suspect you're confused by the type of the pointer, Shape*, which says "the address I hold, if not null, will represent an object of type Shape". It's necessary for both pointer arithmetic and type checking, but doesn't change the simple fact that a pointer holds an address, not an object.

Narue 5,707 Bad Cop Team Colleague

Wouldn't it be better if we just defined the functions before the main function instead of having a function prototype and a function definition in separate areas?

What if you want to break your program up into multiple files? What if you want to write a library that will be used in multiple programs?

Narue 5,707 Bad Cop Team Colleague

Yes.

Narue 5,707 Bad Cop Team Colleague

Replacement for getch() - getche() (similiar functioning)

If you don't have getch() or don't want to use getch() for portability reasons, getche() is a non-solution because it comes from the same library and has the same portability limitations.

Narue 5,707 Bad Cop Team Colleague

I can't flag the post as bad as it is not a post it is a reputation comment.

You can always PM a moderator or admin with any concerns. We won't bite, I swear. ;) But as far as reputation goes, it's inherently subjective, so we'll typically not retract rep unless the comment breaks Daniweb's rules (eg. it's offensive or obscene). But it never hurts to ask.

Narue 5,707 Bad Cop Team Colleague

look i am using getch to input and all other chars are working but enter and delete keys are not working.

This doesn't change my answer.

Narue 5,707 Bad Cop Team Colleague

can you please explain more clearly!!!!!!!

I'll spell it out for you: G. O. O. G. L. E

Narue 5,707 Bad Cop Team Colleague

You have to go into non-standard specialized code that most compilers do not contain.

You say that as if the code isn't already completely non-standard and clearly based on libraries supported by Turbo C. Just say "use getch()" and be done with it, since this is a time when getch() is warranted. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

Let's start with this:

while(c=getchar()!=EOF)

You're missing parens around c=getchar() , which means that the expression is evaluated as c = (getchar() != EOF) rather than (c = getchar()) != EOF .

Narue 5,707 Bad Cop Team Colleague

Thread title changed to be more informative.

Narue 5,707 Bad Cop Team Colleague

At most this would be a popularity contest, and I think that's what the OP intended.

Maybe you people can show some statistics in a regular basis

Statistics don't say much. Going by numbers, the mod who formats and adds code tags to 100 posts had a greater impact than the mod who proactively banned a single spammer account. But in reality the potential negative effect of letting a spammer run rampant for even an hour makes the net impact of the ban unknowable.

Or consider a mod who resolves disputes through PM versus a mod who polices quality control in forums through replies rather than the infraction system? There are no numbers from that, and thus, no statistics despite the significant amount of effort involved.

After-all the ones working in the background should get some spotlight & should be acknowledged.

It's a thankless job to be sure, but rather than look for the "best" moderator, I think a better way to show your appreciation is simply to thank the whole team. We all work together for the greater good, after all. ;)

Narue 5,707 Bad Cop Team Colleague

is there a better way to store strings into an array than using strcpy()?

You could write directly to the array, but if you have an existing string in memory and need to copy it to an array then strcpy() is one of the better options. Though keep in mind that if the source string exceeds the length of your destination array, strcpy() doesn't stop you and you'll introduce a bug. You'll want to check lengths first:

char dst[MAX_LEN];

if (strlen(src) > sizeof dst) {
    /* Handle the error, usually by extending memory or truncating the source string */
}

strcpy(dst, src);

If you don't care about potentially losing data on long source strings, the conventional method for safely "storing" a string is strncat():

dst[0] = '\0' /* This part is important! */
strncat(dst, src, sizeof dst);

There are two interesting questions that arise from this convention:

  1. Why set the first element of dst to '\0'? Because strncat() concatenates strings, and because of this expects dst to be a valid string (unlike strcpy()). The definition of a valid string is a potentially empty sequence of characters terminated with '\0'. Thus setting dst[0] to '\0' makes dst an empty string, which forces strncat() to start copying at the beginning. Failure to do this could potentially result the serious bug of calling strncat() with an uninitialized destination string.
  2. Why use strncat() instead of strncpy()? If you go by names then strncpy() makes more sense because you want strcpy() …
Narue 5,707 Bad Cop Team Colleague

writing only 2 lines for a problem doesn't tell everything which i want. u can help me by telling the proper way of doing this question. i am just a beginner. i don't understand like you because you all are a high-fi professional in C.

Sorry dude, but at some point you'll need to engage your brain. We didn't become "hi-fi professionals" in C by expecting other people to do our thinking for us. You'll get better results by trying something and then asking a smart question about something specific rather than the tired old "I'm a beginner, tell me how to do XYZ".

Narue 5,707 Bad Cop Team Colleague

Yes, i want the space to be inserted when you press enter, without jumping to the next line. And when the maximum number of columns in a row is reached, it should jump on to the next line ie. the new row....

Assuming you want the console to auto-format itself according to the size of your matrix, this cannot be done without taking control of the console in a non-standard way. It's not terribly difficult, but I'd question the practicality of replacing the console with your own custom shell for the sole purpose of formatting matrix input.

Here's a very naive example of the concept:

#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <conio.h>

using namespace std;

string raw_gets()
{
    string result;
    int ch;
    
    // Naive algorithm, use at your own risk
    while (!isspace(ch = getch())) {
        result += (char)ch;
        cout << (char)ch;
    }
    
    return result;
}

int main()
{
    int mat[2][4];
    
    cout << "Enter the matrix:\n";
    
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 4; j++) {
            stringstream conv(raw_gets());
            int x;
            
            conv >> x;
            mat[i][j] = x;
            
            cout << (j < 3 ? ' ' : '\n');
        }
    }
    
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 4; j++)
            cout << mat[i][j] << ' ';
            
        cout << '\n';
    }
}
PrimePackster commented: Thank U very much +3