Narue 5,707 Bad Cop Team Colleague

i and j will never be equal when the item count is even. You're swapping both halves of the array in that case, which ultimately produces the original sequence. Perhaps instead of using that weird logic for your swapping loop, just use the relationship of i and j as the primary condition:

void swap(int a[N])
{
    int i, j;
    
    for (i = 0, j = N - 1; i < j; i++, j--)
    {
        a[i]=a[i]+a[j];
        a[j]=a[i]-a[j];
        a[i]=a[i]-a[j];
    }
}
Narue 5,707 Bad Cop Team Colleague

Your second comment is that C is still after many years the main programming language

Being "honored" (or even "widely used") and being the "main programming language" are two completely different things.

So i tell you what, THINK about your replies before you post them, thanks a lot dear!

Follow your own advice and all will be well. :)

Narue 5,707 Bad Cop Team Colleague

I don't know what to search for.

...

I don't know what to search for.

...!?

I don't know what to search for.

How could you not know what to search for?! You knew how to ask other people for help, and that's most of the way toward defining search keywords. I even linked to an Amazon search for you that produced a few thousand results. From there you can refine the search.

I can't decide if you're completely hopeless or simply lazy. Either way, I'm done here.

Narue 5,707 Bad Cop Team Colleague

They provide a search feature for that reason. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

Have you tried amazon? I'm sure there are plenty of decent books on the basics of how computers work.

Narue 5,707 Bad Cop Team Colleague

is there any other way to specify the command line arguments than by running the program through the cmd followed by "$ ....."?

As my previous post stated, most IDEs will support sending command line arguments to the debugger, but how you do that varies between them. So the answer is yes, but I can't be specific without knowing what compiler and perhaps IDE you use.

Narue 5,707 Bad Cop Team Colleague

It means you should declare a function before using it.

Narue 5,707 Bad Cop Team Colleague

There's no prototype in scope for simple_readline() when you use it, and the arguments you provide, while compatible, don't exactly match the definition. The fix is to add a prototype for simple_readline() before main().

Narue 5,707 Bad Cop Team Colleague

And have you understood the format of the file yourself? if so, do you mind explaining it to me.(since OP doesn't seem to interested in explaining that, he has got his own problems).

It looks to me like an NxN matrix defining the word search followed by the words hidden in the matrix. The matrix is A letter followed by a space, and each row is terminated with a newline.

The only problem with the format is that there's no clean separation between the matrix and the word list. By my reckoning, a little introspection is needed in parsing the file. I chose to use the second character in the line to determine whether we're looking at a matrix line or a word list line (ie. either a space or not), and that seems to work well even though it's a bit ugly:

#include <ctype.h>
#include <stdio.h>
#include <string.h>

#define N 22

int main(void)
{
    FILE *in = fopen("test.txt", "r");
    
    if (in != NULL) {
        char matrix[N][N];
        char line[BUFSIZ];
        size_t row = 0;
        size_t col;
        
        while (fgets(line, sizeof line, in) != NULL
            && isspace(line[1])
            && row < N)
        {
            size_t i;
            
            for (i = col = 0; line[i] != '\n' && col < N; i += 2, col++)
                matrix[row][col] = line[i];
                
            ++row;
        }
        
        for (row = 0; row < N; row++) {
            for (col = 0; col < N; col++)
                printf("%c ", matrix[row][col]);
                
            putchar('\n');
        }
        
        do {
            line[strcspn(line, "\n")] = '\0';
            puts(line);
        } while (fgets(line, sizeof line, in) …
Narue 5,707 Bad Cop Team Colleague

Visual C++ 2010 Express, Code::Blocks (MinGW's gcc), and Pelles C are all good.

vedro-compota commented: ++++++++++++ +3
Narue 5,707 Bad Cop Team Colleague

Why shouldn't i use the getchar() ? is this dangerous too?

getchar() is the recommended way to pause before termination:

#include <stdio.h>

void discard_line(FILE *in)
{
    int ch;

    clearerr(stdin); /* We might be in an error state prior to the call */

    do
        ch = getchar();
    while (ch != '\n' && ch != EOF);

    clearerr(stdin); /* Reaching an EOF state is possible */
}

void pause_execution(void)
{
    discard_line(stdin);
    fputs("Press Enter to continue...", stdout);
    fflush(stdout);
    getchar();
}

int main(void)
{
    /* ... */

    pause_execution();

    return 0;
}

Narue , my compiler doesn't think that

char a='';

is error....

Your compiler neglects several errors in that code, it doesn't mean they're not errors. Turbo C is an exceptionally old compiler. It supports C89 to a decent extent, but you're likely to encounter some frustrating limitations due to the 16-bit architecture (on top of limitations from C's evolution since then). As such, my recommendation is to drop that compiler and get a newer one.

Narue 5,707 Bad Cop Team Colleague

You won't find a book with complete details, the topic is far too broad.

Narue 5,707 Bad Cop Team Colleague

I am aware that it can be a slow programming language

Any programming language can be slow in the wrong hands. Java is notorious for being slow not because it's actually slow, but because it's accessible. Java is easy to learn and it's easier to write complex software without a significant learning curve. Unfortunately, that learning curve is where most programmers learn important lessons such as how to write "good code" rather than just "working code".

Narue 5,707 Bad Cop Team Colleague

the parameters taking of printf function is from right to left.....

Don't confuse how C works on your implementation with how C is specified to work. There's no requirement that parameters be pushed right to left. They could be pushed left to right, or evens then odds, or staggered using the Fibonacci sequence (though right to left and left to right are the most common ;)).

So first it executes the condition b<9 but here b=1
next it executes the condition b>9. Here also b=1

How can b be both less than and greater than 9? Are you using New Math?

i get this but why it happens only in case of printf???

It doesn't happen only with printf():

#include <stdio.h>

void foo(int a, int b, int c)
{
    printf("a = %d\n", a);
    printf("b = %d\n", b);
    printf("c = %d\n", c);
}

int main(void)
{
    int val = 1;
    
    /* Beware! Here be dragons (nasal demons) */
    foo(val = 15, val > 9, val < 9);
    
    return 0;
}
Narue 5,707 Bad Cop Team Colleague

You can't have executable code outside of a function body. Move those parts to main():

int random_event_number;

int main()
{
    srand(time(NULL));

    random_event_number = rand() % 100 + 1;

    ....
}
Narue 5,707 Bad Cop Team Colleague

Are you really running DOS, or just a simulated DOS in Windows? Anyway, it's the same as Windows: Ctrl+Z.

Narue 5,707 Bad Cop Team Colleague

try this.

printf ("%d\n", EOF);

That's how you find out what the value of EOF is, but it's useless information. The value of EOF doesn't correspond to a key code, and can vary between compilers.

Narue 5,707 Bad Cop Team Colleague

EOF is a macro defined in <stdio.h>. It's not the value of a keypress, rather it's an "impossible" value returned by various input functions to signal that end-of-file was detected.

Which key corresponds to "end of file" on the keybord??

That depends on your operating system. On Windows systems the key combination is Ctrl+Z. On Unix, Linux, and Mac OSX systems, the key combination is Ctrl+D. If you're not on one of those (they're the most common around here), please specify.

Narue 5,707 Bad Cop Team Colleague

Done. :)

Narue 5,707 Bad Cop Team Colleague

okay, it works except for it doesn't show the first word of the entered text. say i pulled the program up and it prompts....what is your name?...then i input...My name is john smith...... it would output...name is john smith. Why?

Without seeing your code, I'd guess that you're still reading the first word separately and then overwriting it with the rest of the line. Perhaps something like this:

#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
    string ans1;
 
    cout << "How are you? ";
    cin >> ans1;
    getline(cin, ans1);
 
    cout << ans1 << '\n';
}
Narue 5,707 Bad Cop Team Colleague

in this, is i++ is a one step instruction or i=i+1?

It really depends on the underlying processor, but any decent compiler will use the most efficient instruction(s) to accomplish the task. Further, this isn't something you should be worrying about, as that kind of micro-management of instructions is often unnecessary.

Narue 5,707 Bad Cop Team Colleague

Is there any pointer operation involved in this?

It's hard to answer your question without a code sample of what you're talking about. Please elaborate.

Narue 5,707 Bad Cop Team Colleague

Only admins can change your name, but we're happy to do so if you tell us what you want your new name to be and the new name isn't already being used.

Narue 5,707 Bad Cop Team Colleague

didn't work my man

My apologies, I assumed you were competent enough to take the minor snippet change I provided and work it into a complete program. Try this:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string ans1;

    cout << "How are you? ";
    getline(cin, ans1);

    cout << ans1 << '\n';
}
NathanOliver commented: People these days +9
Narue 5,707 Bad Cop Team Colleague

I think remember hearing someplace that returning in the middle of a method is bad for some reason.

The "some reason" is it's been argued that having multiple returns from a function makes the function harder to read, reason about, and verify for correctness. It's not a universal opinion; the other perspective is that such an argument takes structured programming to an unreasonable extreme.

So, if anyone has any ideas/thoughts/input I'd like to hear them!

They're both perfectly valid. I'd say use whichever option makes the most sense on a case-by-case basis.

Narue 5,707 Bad Cop Team Colleague

Other way as in creating a getter function and calling it with obj3.getValue()? Would it work that way?

That's one option, yes.

Narue 5,707 Bad Cop Team Colleague

So whenever I want to cout the results from adding 2 objects I have to overload '<<'?

No. If you define a type and want cout << obj; to work (where obj is an object of the new type), there has to be an overloaded operator<< for that type. Otherwise you need to figure out some other way of supporting stream output. Overloading operator<< is for consistency with built-in types when you define a type that needs to support being written to a stream.

How does the I/O operators work?

Magic. :D But seriously, that's a can of worms that you probably don't want to open just yet. Start by learning how to use the feature, then later you can dig down into how it actually works under the hood.

Will it always start out as "(ostream &something, const classname& obj)"?

For the most part, yes.

Also do I always have to pass the values in by reference?

The stream object must be passed by reference because there's no copy constructor. You can do whatever you want with the other parameter, but it's generally wise to pass by reference for performance reasons, and by const reference if you don't intend to modify the state of the object.

Narue 5,707 Bad Cop Team Colleague

Since obj3 is default constructed, you need a default constructor. The default constructor is only provided for you if you don't already have another constructor defined. Adding default arguments to your two argument constructor will have the same effect though.

Also, you're trying to send obj3 to cout directly, but there's no operator<< defined for testClass.

Finally, and this is the direct issue you're having with operator overloading, operator+ isn't returning a testClass object, it's returning a double (specifically, a.num2 + b.num2 due to the comma operator). Since you're trying to call the constructor directly, you need to specify the class type:

#ifndef TESTCLASS
#define TESTCLASS
#include <ostream>

using namespace std;

class testClass
{
public:
    testClass(double = 0, double = 0);
    friend testClass operator+(testClass& a, testClass& b);
    friend ostream& operator<<(ostream& out, const testClass& obj);
private:
    double num1, num2;
};

testClass::testClass(double numA, double numB)
{
    num1 = numA;
    num2 = numB;
}

testClass operator+(testClass& a, testClass& b)
{
    return testClass(a.num1 + b.num1, a.num2 + b.num2);
}

ostream& operator<<(ostream& out, const testClass& obj)
{
    return out << obj.num1 << ',' << obj.num2;
}

#endif

#include <iostream>
//#include "testClass.h"
#include <string>
using namespace std;
int main()
{
    testClass obj1(1.1,2.2);
    testClass obj2(2.2,3.3);
    testClass obj3;

    obj3 = obj1 + obj2;

    cout << obj3 << endl;
    return 0;
}
Narue 5,707 Bad Cop Team Colleague

You have two issues. First, the condition should be while (temp2 != NULL) because you want to include the last node in the search. Second, your search loop doesn't update temp2; the loop is infinite. Compare and contrast:

while(temp2 != NULL) {
    if(search == temp2 -> ID) {
        cout << "ID\tName\n";
        cout << temp2 -> ID << "\t" << temp2 -> name << endl;
        decision = 0;
    }
    
    temp2 = temp2 -> link;
}
Narue 5,707 Bad Cop Team Colleague

The output is undefined because commas in a function argument list don't act as sequence points. The rule states that if you modify an object, it may be modified only once between sequence points and only accessed to determine the new value. Your printf() statement breaks the latter part of that rule.

Even if it weren't undefined, the behavior would be unspecified because functions are allowed to push arguments in any order. The output could just as easily be 15,1,0 as 15,0,1 depending on whether the b=15 expression is pushed first or last.

Narue 5,707 Bad Cop Team Colleague

The problem isn't your data type, it's your input method: the >> operator stops reading at whitespace. To read a full line, use getline() instead:

string ans1;

cout << "How are you? ";
getline(cin, ans1);
Narue 5,707 Bad Cop Team Colleague

The compiler is right, LINE_MAX doesn't exist unless it's a library extension. I'd suggest the standard BUFSIZ, but that still won't work either because your code is severely broken. You're working with uninitialized pointers.

vedro-compota commented: +++++++ +3
Narue 5,707 Bad Cop Team Colleague

Do you mind explaining what exactly is happening in that code?

It's extracting the bytes from most significant to least significant by shifting and masking away all but the least significant byte:

01010101111111110000000011110000
00000000000000000000000001010101 -- Shift right 24 bits
                        01010101 -- Mask the low byte

01010101111111110000000011110000
00000000000000000101010111111111 -- Shift right 16 bits
                        11111111 -- Mask the low byte

01010101111111110000000011110000
00000000010101011111111100000000 -- Shift right 8 bytes
                        00000000 -- Mask the low byte

01010101111111110000000011110000
                        11110000 -- Mask the low byte

Each of those bytes are then assigned to a smaller type (uint8_t).

NerdyChick27 commented: Not only did narue help solve something that I've been working for hours, but helped me understand a new concept as well. Thanks! +0
Narue 5,707 Bad Cop Team Colleague

What can I do to isolate a byte from a uint32_t typedef?

You can use the bitwise operators to split your 32-bit value into four bytes:

uint32_t value;
uint8_t bytes[4];

/* ... */

bytes[0] = (value >> 24) & 0xFF;
bytes[1] = (value >> 16) & 0xFF;
bytes[2] = (value >> 8) & 0xFF;
bytes[3] = (value & 0xFF);
Narue 5,707 Bad Cop Team Colleague

The message that the thread is older than N days is located directly above the Quick Reply.

And it clearly doesn't work very well judging by the number of bumped threads with a post that should be a new thread. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

I may have a slightly better idea. Instead of making the new thread button more prominent, how about placing a date check script on the reply buttons? If the thread is older than N days, a nuisance popup could be used. The popup would give posters the option of creating a new thread (the default option) or confirming that they really want to reply to an older thread.

Narue 5,707 Bad Cop Team Colleague

mvprintw() takes a variable argument list, not a va_list object. A cursory (pun intended) look at the documentation shows that vwprintw() takes a va_list, but doesn't support the coordinates. So your next step would probably be figuring out how to set the coordinates before a call to vwprintw() as that would produce the desired behavior.

Narue 5,707 Bad Cop Team Colleague

You cannot declare arrays like that.

Yes, but only because the OP is clearly not compiling as C99. I can tell because main() uses implicit int, which was removed in C99.

Here either 'n' should be initialized prior to declaring array

printf("Enter size:");
scanf("%d",&n);
int a[n];

Um, no. Since this is C90[1], array sizes must be a compile time constant. If the above code compiles, it's due to a compiler extension. The C99 standard added variable length arrays (VLAs for googlers), but I strongly discourage their use in robust code. If you want an array sized at runtime, C99 best practice and C90's only portable practice is dynamic allocation:

int *a;
int n;

scanf("%d", &n);
a = malloc(n * sizeof *a);

...

free(a);

On a side note, C90 doesn't allow the mixing of declarations and code. C99 does, but we've already established that this code isn't C99. C++ allows it as well, which suggests that you're compiling as the wrong language (on top of relying on compiler extensions). The problem is that C++ and C are subtly different. If you don't know where the differences lie, you could end up with difficult to trace bugs.

or n should be replaced by some constant value.

That's better, but only if the size is fixed and unlikely to change. Beginners and poor programmers often subscribe to the theory of "640K ought to be enough for anybody", where if you allocate a large enough array to handle all expected input, …

Narue 5,707 Bad Cop Team Colleague

You can write a few non-member friend operators with arguments covering the different cases:

class Element {
    double number;
public:
    Element(double init): number(init) {}

    friend Element operator+(const Element& lhs, double rhs);
    friend Element operator+(double lhs, const Element& rhs);
    friend Element operator+(const Element& lhs, const Element& rhs);
};

Element operator+(const Element& lhs, double rhs)
{
    return Element(lhs.number + rhs);
}
 
Element operator+(double lhs, const Element& rhs)
{
    return Element(lhs + rhs.number);
}
 
Element operator+(const Element& lhs, const Element& rhs)
{
    return Element(lhs.number + rhs.number);
}

By the way, allocating memory with new and then returning the dereferenced object is just begging for a memory leak.

fruitymo commented: Thank you :-) as for my memory leaks, will take care of it and check them using Valgrind. +1
Narue 5,707 Bad Cop Team Colleague

Why would absolute beginner, that does not know how to use rand(), use vectors?

What's wrong with vectors? I assume you're suggesting that arrays be used instead, which is silly. C++ doesn't have to be learned from the bottom up. In fact, learning C++ with an eye toward realistic code (using available libraries to make things easier) is generally a better approach for two reasons:

  1. Beginners can start writing powerful code much sooner. There's a lot of prerequisite knowledge and experience required to simulate what std::vector does versus simply using std::vector from day one.
  2. Many of the lower level aspects of C++ are both unnecessary and also unnecessarily complex for a beginner.

I was programming C++ for a year and a half now, and I just learned what vectors are a month ago!

So? All this implies is that you've ignored the more useful parts of the standard library for far too long.

L7Sqr commented: Agreed. 100% +7
Narue 5,707 Bad Cop Team Colleague

Right now I have a snippet of code that makes logical sense but in fact doesn't work

Actually, that snippet makes no sense at all. If you're looking to write a bigint library, then your best bet would be to find a simple one and study the code. A good start is to implement the most basic arithmetic in the simplest manner possible. For example:

#include <algorithm>
#include <iostream>
#include <ostream>
#include <string>

namespace jsw {
    class integer {
        std::string _base;
    public:
        integer(const char *init = "0");
        integer(const std::string& init = "0");
        integer add(const integer& rhs);
        friend std::ostream& operator<<(std::ostream& out, const integer& obj);
    };
    
    integer::integer(const char *init)
        : _base(init)
    {}

    integer::integer(const std::string& init)
        : _base(init)
    {}

    integer integer::add(const integer& rhs)
    {
        using std::string;
        
        string::size_type x = _base.size() - 1;
        string::size_type y = rhs._base.size() - 1;
        int carry = 0;
        string result;
        
        // Add two digits while there are more
        while (x < string::npos && y < string::npos) {
            int sum = carry + (_base[x--] - '0') + (rhs._base[y--] - '0');
            carry = sum / 10;
            result.push_back(sum % 10 + '0');
        }
        
        // Fill in the rest
        while (x < string::npos) {
            int sum = carry + (_base[x--] - '0');
            carry = sum / 10;
            result.push_back(sum % 10 + '0');
        }
        
        while (y < string::npos) {
            int sum = carry + (rhs._base[y--] - '0');
            carry = sum / 10;
            result.push_back(sum % 10 + '0');
        }
        
        // The result was built backward, fix it
        std::reverse(result.begin(), result.end());
        
        return integer(result);
    }

    std::ostream& operator<<(std::ostream& …
Narue 5,707 Bad Cop Team Colleague

now that I added more options it's not working and now I'm lost, any expert advice or tips from a second pair of eyes?

My advice is roll back to something that works and add new options more carefully. For example, add debugging output such as the contents of the stack and the values you're testing at each step.

Narue 5,707 Bad Cop Team Colleague

You mean highest in order of precedence?

If I meant that, I would have said that. My words were carefully chosen. Think in terms of an expression tree and you'll understand what I meant:

(i = 15) || (j = 29)


         ||

   =           =

 i   15      j   29

Shouldn't we simply follow the precedence order blindly?

No, because precedence isn't the only thing involved. You also have associativity and order of evaluation. In the above example, the order of evaluation is left to right with short circuiting. Parentheses around a sub-expression don't alter the behavior of the parent operator, but they can certainly alter what is viewed as a sub-expression. Consider this:

i = 15 || (j = 29)

Removing parens on the left expression changes things drastically:

i = 15 || (j = 29)


  =

i      ||

    15       =

           j   29

That's the difference in precedence here, not the evaluation order of ||'s sub-expressions. Blindly evaluating everything in parens first and unconditionally is a start, but it's not a perfect guideline. If you don't want to go to the trouble of learning how complex expressions are parsed, just break them down and remove all ambiguity:

int i = 5, j = 10;
int cmp;

i = 15;
j = 26;
cmp = i || j;

printf("%d\n", cmp);
printf("%d %d\n", i, j);

This produces the output you originally expected.

Narue 5,707 Bad Cop Team Colleague

Functions need to be declared prior to the main() function.

To be precise, functions need to be declared before they can be called.

Narue 5,707 Bad Cop Team Colleague

Thanks Saith and Cross213,though what does Cross213 mean by?

He means (I hope) that the prototype introduces enough information about a function to safely call it without requiring the function's definition to be visible.

Narue 5,707 Bad Cop Team Colleague

so i need to create global variable for my struct is it?

You should avoid global variables, but if it simplifies things for now, so be it.

ive try to create global variable earlier but somehow it gives error.

You haven't posted the code, so I can't say what you did wrong.

i became confuse when struct and pointer are use together.

Then don't. Your use of pointers is unnecessary anyway, it's just adding a pointless level of indirection when you could simply touch the customer object directly.

If I were your instructor and asked for a program using structures and pointers, I'd expect something like this:

#include <iostream>

struct info {
    char name[40];
    int price;
};

void input(info *customer);
void print(const info *customer);

int main()
{
    info customer;
    
    input(&customer);
    print(&customer);
}

void input(info *customer)
{
    std::cout << "Name: ";
    std::cin.getline(customer->name, sizeof customer->name);
    std::cout << "Price: ";
    std::cin >> customer->price;
    std::cin.ignore();
}

void print(const info *customer)
{
    std::cout << customer->name << ":\t" << customer->price << '\n';
}
Narue 5,707 Bad Cop Team Colleague

sirknieghf, you need to learn how local variables work:

void foo()
{
    info customer; // An info object is created

    customer.price = 123; // The info object is modified

} // The info object is destroyed

All of your functions are treating the customer object as if it's magically saved somewhere for reuse, but it's not. You keep recreating an uninitialized info object every single time; naturally the values won't be what you want.

You need to either pass around an info object, or use a global variable, anything that persists the object across the lifetime of your program.

Narue 5,707 Bad Cop Team Colleague

Your pause at the end isn't really pausing because there's extraneous characters in the stream. Specifically, when reading an integer, the [Enter] key you pressed will remain in the stream for cin.get() to read later. You'll find that if you call cin.get() a second time, it'll work as intended, which highlights the issue quite well.

Narue 5,707 Bad Cop Team Colleague

When it tries to analyse (i=15)||(j=29),it must use some operator precedence.

Yes. || is the top of that expression, with left to right short circuit behavior. Consider (i = 15) + (j = 29) , + is the top of the expression, but since there's no short circuit behavior, both parenthesized expressions are evaluated prior to +.

With (i = 15) || (j = 29) , the precedence is the same, but short circuit behavior requires that the left expression be fully evaluated and tested to be false before the right expression can be evaluated.

Narue 5,707 Bad Cop Team Colleague

What have you tried? We're not going to give anything away unless you put forth some effort first.