Narue 5,707 Bad Cop Team Colleague

Apparently sarcasm is not as easy to detect through text as it is in person....

A cross we of the dry wit brigade must all bear.

By the way, do YOU have any information regarding PID controllers (sorry for being shameless)

Not that couldn't be gleaned from a similar Google search that I would use to fake sounding knowledgeable. ;) But for actually addressing your problem, faking it won't help.

Narue 5,707 Bad Cop Team Colleague

Is there any reason why the 3rd is not recommended?.. since it was the one I learned in my notes..

Global variables are difficult to work with in larger programs because they can be accessed from anywhere. Bugs where you find yourself asking "where did that variable get changed?" are greatly complicated by variables with unrestricted access.

Anyways the 'Return Method' will always work

Not always, but it should be your go to method.

Narue 5,707 Bad Cop Team Colleague

Well, seeing as no one seems to be taking my deadline as seriously as I

I would think that's obvious. Your deadline means nothing to us, and many of us are perverse enough to respond more slowly to "urgent" questions. Let's also not fail to notice that it's unreasonable to get angry that nobody in the narrow audience of VB6 PID controller writers hasn't replied after a mere two hours. :icon_rolleyes:

Narue 5,707 Bad Cop Team Colleague

How can I print it from the main? I know it sounds stupid, but I am still a beginner to the language.

There are three conventional options for accessing the calculated result in a function from the calling function:

  1. Return the result from your function:
    #include <stdio.h>
    #include <math.h>
    
    float round2int(float test)
    {
        return floor(test + 0.5);
    }
    
    int main (void)
    {
        float x;
        
        while (1) {
            printf("Enter a number (Enter zero (0) to quit program): ");
            scanf("%f", &x);
            
            if (x == 0)
                break;
                
            printf("%f\n", round2int(x));
        }
        
        return 0;
    }
  2. Pass a pointer to the destination object as an argument:
    #include <stdio.h>
    #include <math.h>
    
    void round2int(float test, float *result)
    {
        *result = floor(test + 0.5);
    }
    
    int main (void)
    {
        float x, result;
        
        while (1) {
            printf("Enter a number (Enter zero (0) to quit program): ");
            scanf("%f", &x);
            
            if (x == 0)
                break;
            
            round2int(x, &result);
            printf("%f\n", result);
        }
        
        return 0;
    }
  3. (not recommended) Use a global variable:
    #include <stdio.h>
    #include <math.h>
    
    float result;
    
    void round2int(float test)
    {
        result = floor(test + 0.5);
    }
    
    int main (void)
    {
        float x;
        
        while (1) {
            printf("Enter a number (Enter zero (0) to quit program): ");
            scanf("%f", &x);
            
            if (x == 0)
                break;
            
            round2int(x);
            printf("%f\n", result);
        }
        
        return 0;
    }
terence193 commented: Well given examples +2
Narue 5,707 Bad Cop Team Colleague

Consider four cases given an array, a start index, and an end index:

  1. The base case where the start index passes the end index: terminate recursion.
  2. There's a vowel at the start index: recurse and increment the start index.
  3. There's not a vowel at the end index: recurse and decrement the end index.
  4. There's a vowel at the end index: swap the characters at the two indices and recurse while both incrementing the start index and decrementing the end index.
Narue 5,707 Bad Cop Team Colleague

But it does not totally work yet.

Your inner loop should start at arraySize - 1 to avoid an out of bounds array access, and end at i rather than 0. Currently by going all of the way to 0, you're undoing work done previously and messing up the result.

Narue 5,707 Bad Cop Team Colleague

Your algorithm is a little goofy. I think a more intuitive algorithm would match the way one might do it manually:

  1. Find the first non-vowel and mark it y, this is the end of the vowel half
  2. Find the next vowel and mark it x
  3. Swap the characters at y and x
  4. Increment y
  5. Repeat at 2 until x reaches the end of the list

This is easily translated to C++, and only requires a way to determine whether the specified character is a vowel:

void vowel_partition(char a[], int n)
{
    int x = 0;
    
    // Find the first non-vowel
    while (x < n && is_vowel(a[x]))
        ++x;
    
    // Swap in any remaining vowels
    for (int y = x; x < n; x++) {
        if (is_vowel(a[x])) {
            std::swap(a[x], a[y]);
            ++y;
        }
    }
}
Narue 5,707 Bad Cop Team Colleague

Function calls use parentheses, not braces:

System.Console.Writeline("this is my program")
System.Console.ReadLine()
Narue 5,707 Bad Cop Team Colleague

I heard I could do this with multithreading (which apparently is very complicated).

You heard correctly. While threading is conceptually very simple, the subtle and difficult to trace errors of shared data access makes it among the harder things that most programmers have to deal with.

Is there any other way to do this?

Not if your goal is to avoid the complexity of threads. Other methods of achieving concurrency are just as complicated.

If not, where should I start to learn about threads and multithreading (I have never used threads/anything like this before)?

Have you tried Google?

Narue 5,707 Bad Cop Team Colleague

Can you please give some examples?

Examples of what?

Narue 5,707 Bad Cop Team Colleague

What are the best practices about using properties in C#?

Best practice is really no different from parameters and return values from functions. If you can get away with a reference, do so. It's generally more efficient for both space and execution time. Not to mention that it's easier to reason about a single object's lifetime than multiple copies of the object.

Narue 5,707 Bad Cop Team Colleague

C should be CONCISE, (short, and to the point), not a Rube Goldberg deluxe creation. Simple and clear are secondary goals to accuracy, but important one's nevertheless.

Concise and clear can easily be mutually exclusive. For example:

#include <stdio.h>

#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
#define min3(a,b,c) (min(a, min(b, c)))
#define max3(a,b,c) (max(a, max(b, c)))
#define mid3(a,b,c) \
    ((a) > (b) && (a) > (c) ? \
        max(b, c) : \
        ((a) < (b) && (b) > (c) ? max(a, c) : max(a, b)))

int main(void)
{
    int x, y, z;
    
    printf("Enter three integers: ");
    fflush(stdout);
    
    if (scanf("%d%d%d", &x, &y, &z) == 3) {
        printf("%d %d %d\n", min3(x, y, z), mid3(x, y, z), max3(x, y, z));
        printf("Sum: %d\n", x + y + z);
    }
    
    return 0;
}

This program does the same thing, but that mid3() macro is a bear even with the helper macros. This is a case where concise might be a bad thing because it hurts clarity.

Narue 5,707 Bad Cop Team Colleague

what thing makes this program print out a rhyme rather than a compiler error

It's not invalid code[1], just very difficult to read. If you really want to understand it, a good start would be reformatting the code into something more sensible. That alone is a decent exercise, but not one I would recommend for a beginner. As already mentioned, at this point you'll learn more by studying good code than intentionally bad code.

I don't think they are non-portable, I compiled them and found a fair amount of success under Code::Blocks 10.05.

So you tested them on one version of one compiler, had a "fair amount" of success, and have the rocks to say that they're portable? Do you understand what portable means?


[1] Technically it is invalid because it's K&R C rather than standard C (the entry was for the 1988 IOCCC, if I recall correctly). Modern compilers will probably fail to run it even if they don't choke on the pre-standard syntax.

Narue 5,707 Bad Cop Team Colleague

can anyone explain to me how this program works.

Can I? Yes, this program is actually very well known as it was an early winner of the IOCCC. Will I explain it to you? No, IOCCC programs are written by very clever people, and the techniques implemented are virtually useless outside of the contest and often non-portable. As a beginner to C you'd be wise to learn from well written code rather than intentionally bad code.

Narue 5,707 Bad Cop Team Colleague

The error makes sense. How do you find "" to replace? Are you trying to replace nothing? Every character? It's ambiguous. In the case where the search string is empty, I'd simply do nothing:

private void btnReplace_Click(object sender, EventArgs e)
{
    if (txtSearchFor.Text.Length == 0) {
        txtReplacedWord.Text = txtInputWord.Text.Replace(
            txtSearchFor.Text, 
            txtReplaceWith.Text);
        txtReplacedWord.Visible = true;
    }
}
Narue 5,707 Bad Cop Team Colleague

Can you tell me why use size_t and not int for orig_len and rep_len?

strlen() returns a value of type size_t. I like to use size_t for array sizing and indexing simply because it's a slightly better fit than int, and the standard library uses size_t extensively for that purpose.

Note that size_t is an unsigned type while int is signed, which has potential for subtle bugs if you mix them.

And what would i need to do so that the program would do the same if return type for function replace_str were void and not char?

You don't need to do anything, really. res is being passed as an argument, so it will be updated in the caller. Just modify the function a smidge to simplify things and you're done:

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

void replace_str(char *res, char *str, char *orig, char *rep)
{
    size_t orig_len = strlen(orig);
    size_t rep_len = strlen(rep);
 
    while (*str != '\0') {
        if (strncmp(str, orig, orig_len) != 0)
            *res++ = *str++;
        else {
            strncpy(res, rep, rep_len);
            str += orig_len;
            res += rep_len;
        }
    }
 
    *res = '\0';
}

int main(void)
{
    char res[BUFSIZ];
 
    replace_str(res, "thisisatest", "i", "foo");
    puts(res);
 
    return 0;
}

However, it is conventional to return a pointer to the beginning of the destination string rather than void in cases like this.

Narue 5,707 Bad Cop Team Colleague

The following code does not work.

Obviously. You're trying to print the return value of a function that returns void.

However, if you remove void in front of replace_str, in Code Blocks i am able to run it (WHY???) despite the fact that i still get a warning

Prior to C99, omitting the return type from a function causes the compiler to assume that you meant int. This is the implicit int rule, and the two following declarations are equivalent:

replace_str(char *res, char *str, char *orig, char *rep);
int replace_str(char *res, char *str, char *orig, char *rep);

It's not wise to rely on this rule though, as mentioned, it no longer exists in the latest revision of the C language.

Plus, i would like to know the correct sintax to print res using printf (the comment in code does not do it).

The bigger problem is that you're pointing res in replace_str() to a different place, not copying the contents of buffer into res . The code should be more like this (for replacing the first occurrence:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 1024

char *replace_str(char *res, char *str, char *orig, char *rep)
{
    char buffer[4096];
    int i;
    char *p;

    if (!(p=strstr(str, orig))) {
        for(i=*p; i<strlen(orig); i++)
            res[i]=str[i];
    } else {
        strncpy(buffer, str, p-str);
        buffer[p-str] = '\0';
        sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
        strcpy(res, buffer); /* Still unsafe... */
    }
    
    return res;
}

int main(void)
{
    char res[SIZE],s1[SIZE],s2[SIZE],s3[SIZE];
    
    scanf(" %s",s1);
    scanf(" %s",s2);
    scanf(" %s",s3);
    puts(replace_str(res, s1, s2, s3)); …
Narue 5,707 Bad Cop Team Colleague

Here's a suggestion to handle threads that should be flagged as solved but haven't been.

Implement a control on the thread with the text "Notify OP to Mark as Solved".

Anyone (or perhaps anyone with a given minimum rep) can click on this control. This would cause an email to be sent to the OP requesting that he/she return to that thread and mark it as solved (perhaps there could even be a link in the email similar to the unsubscribe link that would accomplish this). To prevent multiple emails, the first click would also set a flag so that the control is disabled and replaced with the text "The OP has been notified to mark this thread as solved".

A special web page, available to moderators, could be created which cummarizes all threads for which the OP has been notified but for which no action by the OP has yet been taken.

The icons on the thread summary pages (new posts, popular thread, you have posted, etc) could be modified (perhaps displayed in red instead of purple) to indicate that a thread has been flagged for cleanup but not marked as solved.

This would put policing in the hands of the DaniWeb community and save the moderators (by virtue of the special web page) from having to scour the threads for cleanup. It would also ensure that OPs are notified that action is required.

It's a nice idea, but also a lot of work for a feature that's largely …

Narue 5,707 Bad Cop Team Colleague
tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height));
Narue 5,707 Bad Cop Team Colleague

nameList is uninitialized. Since you're always using realloc() to allocate memory to nameList, it should be initialized to NULL for the first allocation to succeed:

char** nameList = NULL;
Narue 5,707 Bad Cop Team Colleague

but it doesn't enable the panel even though i use bringtofront(), enabled and visible?

Then you're not doing something correctly, because that's pretty much how one would swap panels in and out of the same real estate on a form. Just out of curiosity, have you considered a tab control? The tab buttons can be hidden, and switching between tab panels is a bit easier than manually implementing the same behavior.

Narue 5,707 Bad Cop Team Colleague

Why are you using ifstream instead of wifstream? If you're working with wide characters, it's generally a good idea to use wide character oriented classes.

Narue 5,707 Bad Cop Team Colleague

Please post a complete test program that exhibits the error.

Narue 5,707 Bad Cop Team Colleague

Is it possible to do something like this with strtok()?

No, strtok() doesn't support rules for embedded delimiters. What you want is more along the lines of a CSV parsing algorithm

Narue 5,707 Bad Cop Team Colleague

The usual methods of storing passwords aren't reversible, so the only option is resetting the password. You can then either email the new password to your users and give them the option of changing it, or invalidate the password and force them to change it rather than risk sending a temporary password in the clear.

For security reasons, the latter option is preferred.

sknake commented: +1 for you posting in the C# forum :) +14
Narue 5,707 Bad Cop Team Colleague

its no difference in string weather you write & or not in string because the string name saves the address it self.
;)

Actually, there's a subtle but significant difference. The address may be the same, but the type is different. If you pass an object of a different type than scant() expects, the result is undefined behavior. In many cases, undefined behavior means working the same way as if the correct type were passed, but that doesn't excuse doing things the wrong way.

Narue 5,707 Bad Cop Team Colleague

please tell me whether this code is right ??????

No, we've already gone over this. The author of your book is a retard, and you can't trust any of the code in it. Actually, you can trust that the code is probably wrong in all examples.

I can only imagine what that example is trying to teach, but it fails to understand the basic concept of a const contract. When you declare an object as const, you're telling the compiler that it won't be modified. If you then go and try to modify it, that's a breach of contract that will either fail to compile, or if you use gratuitous casts to force the operation, probably fail to execute successfully.

Let me reiterate: your book is shit. Get a new one. Otherwise the process of learning C will be ten times longer because you'll have to unlearn all of the bad habits this book will teach you.

Narue 5,707 Bad Cop Team Colleague

You only need to show the invalid prompt if the entered value was actually invalid:

printf("Enter a positive number: ");
fflush(stdout);

/* I'm ignoring non-integer input for now to keep things simple */
scanf("%d", &x);

while (x <= 0) {
    printf("Invalid input. Please try again: ");
    fflush(stdout);
    scanf("%d", &x);
}
Narue 5,707 Bad Cop Team Colleague

but can you show me the full code?

Nope. The code you posted isn't even close to a voting program, so I can't justify giving you "full code" as it would constitute doing your homework for you.

i can't assemble these 2 parts

It sounds to me like you're overwhelmed and need to start smaller. Here's a good thread on the iterative development process. The only part that's missing is organizing your thoughts beforehand, and having a strong idea of how the program should work (in simple steps, like a flowchart) before writing any code.

Narue 5,707 Bad Cop Team Colleague

What else could cause a seg fault on the last line of code no matter what that line of code is?

Corrupted memory that only manifests in the destructor is a good start.

Narue 5,707 Bad Cop Team Colleague

Well, arrays are indexed starting at 0, so if you want to map 1 to the first name, it would be users[index - 1] . Then all you need to do is ask the user to enter a number corresponding to the person they want to vote for.

Your loop has an off-by-one error, by the way. It should stop at 3 because that's the last valid index:

for(int i = 0; i < 4; i++) {
Narue 5,707 Bad Cop Team Colleague

I have a text file with 10 lines, one word on each line and I am trying to get a word from a random line and then cout that word.

Take note that since there's only one word on each line, the problem can be restated as trying to get a random line. That's a smidge simpler than a random word where each line can have multiple words.

In fact, you can do it without storing all of the lines as in thines01's example. For ten lines using a vector isn't a big deal, but if you want to find a random line in a huge file (on the order of gigabytes) then it's wiser not to read the whole thing into memory. Here's an (intentionally advanced) example:

#include <algorithm>
#include <climits>
#include <cmath>
#include <cstddef>
#include <ctime>
#include <functional>
#include <fstream>
#include <iostream>
#include <map>
#include <random>
#include <string>
#include <utility>

unsigned time_seed()
{
    std::time_t now = std::time(nullptr);
    unsigned char *p = (unsigned char*)&now;
    unsigned seed = 0;

    for (std::size_t i = 0; i < sizeof now; i++)
        seed = seed * (UCHAR_MAX + 2U) + p[i];

    return seed;
}

class random_line
{
public:
    random_line(): generator(time_seed()) {}

    std::pair<long long, std::string> operator()(const char *filename) {
        std::ifstream in(filename);
        std::string line;

        if (in && std::getline(in, line)) {
            std::string picked_line = line;
            long long picked_index = 0;
            long long i = 0;

            // Reservoir sampling method so we don't have to store all lines
            do {
                auto random = std::uniform_int_distribution<>(1, ++i); …
Narue 5,707 Bad Cop Team Colleague

And why these address are fixed.

The addresses aren't fixed, but the likelihood of the addresses being right next to each other is pretty good. Here's my output (after fixing your Turbo C crap boilerplate):

Address of i=28ff18
value at ptr=10
Address of j=28ff14
value at ptr=20

Notice that the difference between the address of i and the address of j is four bytes, which is understandable because my implementation uses 32-bit integers. Your implementation uses 16-bit integers because it's as old as dirt, hence the two byte difference.

Note that this has nothing to do with the const keyword, it's completely how the compiler chooses to allocate memory for local variables.

Narue 5,707 Bad Cop Team Colleague

Is it the person who posted the solution or the lurker who made the last (but not helpful) post?

It's both, to the best of my knowledge. Everyone who posted prior to the thread being marked as solved (except for the OP, of course) will have their solved thread count incremented.

Narue 5,707 Bad Cop Team Colleague

It's certainly confusing, but straightforward once the concept is understood. Formatted input methods ignore leading whitespace. Unformatted input methods don't ignore leading whitespace. The newline character is whitespace. Finally, getline() terminates when it detects a newline.

So the pattern where getline() is "skipped" would be formatted input followed by getline(), which is unformatted:

cin >> x;
getline(cin, y); // Likely to be "skipped"

Now, I say "skipped" because getline() isn't really being skipped. It's being called and successfully terminating after reading the first character, which is a newline. The reason people say it's being "skipped" is because they don't realize the newline is there or what it represents to getline().

Narue 5,707 Bad Cop Team Colleague

I noticed that, getting user imput, conditional statements, using escape charecters, exicuting system commands, and even declaring variables and using them so that they have use; these are all difficult outside of the domain of C and C++

Hahaha! No. ;)

even the merciless Java can't do it without several lines of code and Java's even more standardized!

Let's do a test:

#include <iostream>
#include <string>

int main()
{
    std::string line;
    
    while (getline(std::cin, line))
        std::cout << line << '\n';
}
import java.io.*;

class Program {
    public static void main(String[] args) throws IOException {
        BufferedReader in(new InputStreamReader(System.in));
        String line;
        
        while ((line = in.readLine()) != null)
            System.out.println(line);
    }
}

Hmm, even for console input (where Java is especially verbose), the two programs are equivalent in length and complexity.

Why?

I'd wager that the reason is you know C and C++ better, have an emotional attachment to them, and even the smallest syntactic difference in other languages causes you to rage irrationally. ;)

Narue 5,707 Bad Cop Team Colleague

So how do I create a constructor in this template class to declare array2 as 0, and arraySize as 0?

You do nothing, because that constructor already exists...

Narue 5,707 Bad Cop Team Colleague
Lottery<int>Lotto();

Welcome to C++, where syntactic ambiguity means you declared a function rather than an object. Remove the parens from this declaration and Lotto will become what you intended it to be:

Lottery<int> Lotto;

And array2 isn't visible in main(), it's a private member of the Lottery class.

Narue 5,707 Bad Cop Team Colleague

Why is using feof() (which is the equivalent of !fin.fail()) as the loop condition wrong?

I posted a link. Basically it's a timing issue. The error flags aren't set until after you try and fail to read from the stream. Unless the loop contains a further sanity check, you'll be working with data from the previous iteration. It's a "the last record is processed twice" situation.

Narue 5,707 Bad Cop Team Colleague

Basic programming algorithms (e.g. accumulated sum/product, random number generation), basic data types and I/O, language constructs (assignment, if, case/switch, loops), higher data structures (including records/structures, arrays and strings), text files, introduction to pointers and function calls by reference

Oh, in that case you'll have a hard time not learning the required material unless you're unusually dense. ;)

Narue 5,707 Bad Cop Team Colleague

I just started learning C yesterday and need to become good at least by next January.

Why the rush? Two months isn't unreasonable for someone with programming experience, but that's predicated on them already being decent programmers and simply picking up the language. But going from zero to "good" would be pushing it, in my opinion, unless you're unusually talented. C is a language with many nuances that can only be understood through experience.

Narue 5,707 Bad Cop Team Colleague

The first problem is you read a number into x and print it out, but don't add it to the sum. The second problem is using fin.fail() as the loop condition, it's basically the same as using feof(), which is wrong.

Try this instead:

// read text from file
int ne(0);
int oe(0);

while (fin >> x) {
    cout << "Read integer: " << x << endl;

    sum += x;

    if (x % 2 == 0)
        ++ne;
    else
        ++oe;
}
Narue 5,707 Bad Cop Team Colleague
if (decision ! 1 || 2 || 3|| 4) {
if (decision != 1 && decision != 2 && decision != 3 && decision != 4) {
    printf("wrong input\n");
}

Previously I assumed you have a book on C, is this not the case? Because a lot of your errors seem a lot like you're guessing about language fundamentals that are clearly explained in every introductory book I can remember.

Narue 5,707 Bad Cop Team Colleague
scanf("%d\n",&decision);

scanf() is not printf(). Remove the newline from that format string because it doesn't do what you think it does.

Narue 5,707 Bad Cop Team Colleague

decision is an integer, yet your if statements are treating it as a character. Note that '1' is not the same value as 1 .

Narue 5,707 Bad Cop Team Colleague

There's an invisible control character on line 33. Delete the line and rewrite it.

Narue 5,707 Bad Cop Team Colleague

how is the boolean condition written though?

Read the chapter again. Assignments aren't given without covering the necessary material, and you don't seem to have been paying attention.

Narue 5,707 Bad Cop Team Colleague

I forgot to mention that this line is preset by my instructor

Then one of the following is true:

  • You misunderstood the requirements of the program.
  • You're expected to use a non-standard compiler extension.
  • Your instructor is setting you up for failure by asking for the impossible.

I'd wager it's the first one, maybe you should verify what your instructor expects. Note that I'm assuming you aren't allowed to use a C++11 solution.

Narue 5,707 Bad Cop Team Colleague

what is a _Bool variable?

A variable of boolean type. The keyword for a boolean type in C is _Bool. It holds only two values: 0 or 1, which correspond to false and true, respectively. C also provides a header called <stdbool.h> that defines more convenient macros: bool , false , and true :

#include <stdbool.h>
#include <stdio.h>

int main(void)
{
    _Bool a = 0; // Without stdbool.h macros
    bool b = false; // With stdbool.h macros

    if (a) {
        printf("True!\n");
    }
    else {
        printf("False!\n");
    }

    if (b) {
        printf("True!\n");
    }
    else {
        printf("False!\n");
    }
}

how is the if then statement written exactly in c?

if (/* boolean condition */) {
    // True case
}
Narue 5,707 Bad Cop Team Colleague

I know what you mean, but nobody is going to enumerate the likely data structures used in each feature supported by facebook just because you're too lazy to pick a specific feature.