Labdabeta 182 Posting Pro in Training Featured Poster

It stops working because you have no code in those sections. If you choose 'B' you will execute this code:

else if (choice== 'B' || choice=='b') {

}

Which of course does nothing. Similarly after you create your arrays you don't do anything with them, so again it stops working.

Meanwhile I doubt you are intended to manually enter a bunch of numbers. You are likely supposed to generate them. To generate a random number between 'low' and 'high' you can do this:

int random = (rand() % (high-low)) + low

You can google search for "rand() C++" for more information.

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I am having a bit of an issue with my networking addition to my game engine. The engine uses SDL to provide an event-driven programming environment. I tried adding networking functionality, but it doesn't seem to work. Here is the relevant code:

//includes
#if defined(_WIN32)
    #include <winsock2.h>
    typedef int socklen_t;
#else
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <fcntl.h>
    #include <unistd.h>
#endif
typedef struct sockaddr_in sockaddr_in;
typedef struct sockaddr sockaddr;

//...

typedef struct Connection {
    int handle; // Socket handle
    void (*onReceive)(void*,unsigned int,unsigned short); // callback(data,ip,port)
    int size; //size of expected received data
};

//...

Connection *init_connection(int size, unsigned short port, void (*onReceive)(void*,unsigned int, unsigned short))
{
    unsigned long nonBlocking = 1; //windows shenanigans
    sockaddr_in address;
    Connection *ret = malloc(sizeof(Connection));
    ret->handle = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if (ret->handle <= 0) {
        free(ret);
        return NULL;
    }
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);

    if (bind(ret->handle,(const sockaddr*)&address,sizeof(sockaddr_in))<0){
        free(ret);
        return NULL;
    }

    //more windows shenanigans
#if defined(_WIN32)
    if (ioctlsocket(ret->handle,FIONBIO,&nonBlocking)) {
        free(ret);
        return NULL;
    }
#else
    if (fcntl(ret->handle,F_SETFL,O_NONBLOCK,nonBlocking) == -1) {
        free(ret);
        return NULL;
    }
#endif
    return ret;
}

//... 

void close_connection(Connection *conn)
{
    //windows ><
#if defined(_WIN32)
    closesocket(conn->handle);
#else
    close(conn->handle);
#endif
    free(conn);
}

//... 

void connection_send(Connection *conn, void *data, unsigned int ip, unsigned short port)
{
    sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = htonl(ip);
    address.sin_port = htons(port);

    sendto(conn->handle,(const char*)data,conn->size,0,(sockaddr*)&address,sizeof(sockaddr_in));
}

//... finally, inside the event loop, after processing SDL events, but before
//framerate calculations and onStep callbacks...

sockaddr_in from;
socklen_t fromlen = sizeof(from);
void *buf = malloc(conn->size);
int numReceived = recvfrom(conn->handle,(char*)buf,conn->size,0,(sockaddr*)&from,&fromlen);
if (numReceived > 0) …
Labdabeta 182 Posting Pro in Training Featured Poster

I'm the same way with javascript, I find it very hard to get anything done. However most C++ constructs do exist in javacript, including multidimensional arrays, for loops, etc. You can easily google for "How to do <something> in javascript" and get loads of answers and examples. Post a first attempt at converting the above program, then we'll help debug it if necessary.

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I am working on a moderately large web development system and have been charged with developing the server-side application for the web site. As a primarily local developer I have by far the most experience in C/C++. My favourite language is Ada, just to give you a sense of how much I value static compile-time error checking.

Thanks to this, I decided to start developing the web server using Wt. After discussing this with my group (this is a 2-year university project) I was met largely with disbelief. I am aware that most web servers are made in interpreted languages such as PHP, Python or Javascript (with Node.js), but I don't see an obvious reason why C++ would be a bad language for web development.

I am familiar with Python and Javascript. I use Python on a semi-regular basis to test my code and javascript regularly to make client-side web applications. Whenever I use these languages I find myself desperately missing the compile-time checking available in compiled languages. This is especially true when it comes to understanding functions. Having a type signature is very helpful when determining what a function does. Essentially it comes down to the fact that I can find a bug in C code in under 30 minutes no matter what, whereas a Python bug can sometimes elude python experts (I have a friend who does everything in python [he was my partner for a VHDL lab in first year and found a Python->VHDL …

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you good sir!

This is exactly what I've been after. My ideal solution was OpenGL without the useless Win32 baggage that usually comes with it. GLFW appears to do just that.

The only downside is that it appears to require some compiled binaries. I understand that it might not be possible to get around this though...

Labdabeta 182 Posting Pro in Training Featured Poster

Hi.

I am familiar with the following C graphics libraries: Cairo, SDL, SDL2, and OpenGL. The problem I have found with these is that they either require shared libraries (Cairo/SDL/SDL2) or are difficult to make cross-platform (OpenGL). I am wondering if there are any graphics libraries for C that do not require the installation of any dll's or so's.

Ideally I would want the library to be extremely light-weight and fast. I do not require 3D rendering capabilities, nor advanced windowing options.

Does such a library exist?

Labdabeta 182 Posting Pro in Training Featured Poster

cin >> t1 >> t2 >> t3 I know that it seems like an unintuitive way to get 3 values from input, but it makes sense once you learn about istreams and the fact that cin is one.

Labdabeta 182 Posting Pro in Training Featured Poster

First of all the code for (a=4; a<5; a=a++) is undefined behaviour, you probably meant for (a=4; a<5; a++) which 'loops' a from 4 to 5 (essentially just running the loop once on the value a=4.

To use a value found inside the loop outside of it, it must be declared outside of it. Therefore your intended code was likely:

while (1) {
    <type> result;
    for (...) {
        ...
        result = ...;
    }
    //use result here all you want
}
Labdabeta 182 Posting Pro in Training Featured Poster

By hand.

What they did was they wrote out the code of the compiler in some slightly-higher language. Then they manually went through the code and compiled it themselves. Once that was done they could use the compiler to compile any future sources.

New compilers would then be 'bootstrapped' using old compilers by writing their code in a language for which a compiler already existed.

Labdabeta 182 Posting Pro in Training Featured Poster

Judging by your code it looks like you are doing Android development and trying to pass data from one activity to another. Due to the nature of Android activities (multithreaded, and can be GC'ed at any moment if, e.g. you get a phone call) you can't deal with passing data between them any of the normal java ways.

This leaves you with a few options which are easily googled for as "Android pass data between activities" or similar.

The following is a summary of the most common techniques.

Option 1: Application-Global values

This is useful if most/all of your activities will require access to the data. To implement it create a class that extends 'Application' and add the class name to the manifest under the <Application> tag. Inside this class you can have public static variables which can be accessed from any activity using getApplicationContext(). Here is an example:

class GlobalApplication extends Application {
    public static int value;
}

class SettingsActivity extends AppCompatActivity { 
    @Override
    protected static void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GlobalApplication me = (GlobalApplication)getApplicationContext();

        me.value = 1;
    }
}

class MainActivity extends AppCompatActivity {
    @Override
    protected static void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GlobalApplication me = (GlobalApplication)getApplicationContext();

        Log.d("Global value is: " + me.value);
    }
}
Option 2: Passing data through intents

If your first activity creates the second via an intent, you can add data to the intent to move values. This is preferred over creating an Application if it can be done. Here is an example:

JamesCherrill commented: Great contribution and clarifies many issues. Thanks. +15
Labdabeta 182 Posting Pro in Training Featured Poster

Functions are used to pack repeated code together. The general form of a function is this:

<return-type> <identifier>(<arguments>)
{
    <body>
}

This means for example that these two programs are effectively identical:

A version with no functions

#include <stdio.h>

int main()
{
    int mode,num;
    printf("Please choose to print (1) Increasing numbers or (2) Decreasing numbers: ");
    scanf("%d",&mode);
    if (mode!=1&&mode!=2)
    {
        printf("Error: invalid mode...\n");
        return 1;
    }
    printf("Please enter the starting number: ");
    scanf("%d",&num);
    if (mode==1)
    {
        //print increasing
        int i;
        for (i=0; i<=num; ++i)
            printf("%d\n",i);
    }
    else
    {
        //print decreasing
        int i;
        for (i=num; i>=0; --i)
            printf("%d\n",i);
    }
    return 0;
}

A version with functions: (note that void means 'nothing')

#include <stdio.h>

//Function to print numbers increasing
void printIncreasing(int num)
{
    int i;
    for (i=0; i<=num; ++i)
        printf("%d\n",&num);
}

//Function to print numbers decreasing
void printDecreasing(int num)
{
    int i;
    for (i=num; i>=0; --i)
        printf("%d\n",&num);
}

int main()
{
    int mode,num;
    printf("Please choose to print (1) Increasing numbers or (2) Decreasing numbers: ");
    scanf("%d",&mode);
    if (mode!=1&&mode!=2)
    {
        printf("Error: invalid mode...\n");
        return 1;
    }
    printf("Please enter the starting number: ");
    scanf("%d",&num);
    if (mode==1)
        printIncreasing(num);
    else
        printDecreasing(num);
    return 0;
}

The benefits of using functions are incredible. For one, they prevent code duplication, so you don't hurt your wrists as much. For another they simplify logic, instead of having your code be one monolithic chunk of statements, you can break it up into manageable bites. They also allow for special techniques to be used to solve …

Labdabeta 182 Posting Pro in Training Featured Poster

In your current code you populate the array with sc.nextInt(), now you want to populate them with random numbers. There is a method called Math.Random() which gives you a random number from 0 to 1 (including 0, not including 1).
You will have to 'stretch' the number you get to the right width (1-20) like so:

MatX[i][j]=(int)(Math.Random()*<Max-Min Here!>)+<Min Here!>;
Labdabeta 182 Posting Pro in Training Featured Poster

First of all that is C++, not C. Second your problem description is poor, however I think I understand what you are after.

Of interest is this code snippet:

//This code returns the n'th cycle of string s
std::string tmp;
for (int i=0; i<s.length(); ++i)
    tmp+=s[(i+n)%s.length()];

The way it works is by starting at an arbitrary position, then 'wrapping-around' back to the start of the string using the modulo operator.

If you get some code to compile, but its giving the wrong result, then maybe we can help you some more.

Stuugie commented: Good on you for figuring this out... +6
Labdabeta 182 Posting Pro in Training Featured Poster

I don't normally resurrect dead threads, but I will make an exception.
These types of esoteric programming problems are often frowned upon for teaching bad programming practices. This is not their purpose.
As the IOCCC explains, these types of problems promote thinking into what might occur that would be bad to see. Awareness of these esoteric features is the goal, not promotion of them.

Now to nail the coffin of people posting their solutions to individual problems in this thread, here is #1-4 in standard compliant C89/99/11:

#include <stdio.h>
#include <stdlib.h>
#define hand ma##in
int hand(int argc, char *argv[]) {
    if (printf("Hello, world!\n")||
        scanf("%d",&argc)){}
    if (argc&1){if(printf("Even")){}}
    else       {if(printf("Odd")){}}
    while (exit(0),0[argv]){}
}

Some truly useful examples of these techniques:

char toHexDigit(int x)
{
    if (x>15) return '\0';
    return x["0123456789ABCDEF"];//legit, even though x is not an array!
}

#define DEBUG(item,desc) (printf(#item ":\t" desc),0)//example
if (!ERROR_HAS_OCCURRED ??!??! DEBUG(ERROR_HAS_OCCURED,"Why?!"))
//you can replace ??!??! with ||, but ??!??! is funny
{
    //deal with error-free code here
}
else
{
    //deal with error-heavy code here
}
Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I posted on this forum two times before about a particular pair of non-printing characters being inserted into my code. You can find the threads here and here. Two great posters tried their best to solve this problem (mike_2000_17 and deceptikon) to no avail.

Finally, using the hints that their responses provided, and a great deal of unhealthy obsession, I dug to the root of the problem. In doing so I uncovered a sort of 'generic response' to finding these kinds of errors. I figured I would share that methodology here.

Step 1: Isolate the characters
In my case, I got stray /302 then /206 in my code, so my characters were /302/206.
Another example is mike_2000_17's stray /302/240, let's analyze that as well.

Step 2: Convert to Hex
Most tools check the hexadecimal, not octal, representation of a character set, for ease of verification convert your characters to hex. Note that the /### notation represents an octal number, so each digit represents 3 bits. Also note that the first digit is never more than 3, so each trio of numbers represents one byte. These two-byte numbers can easily be written as 4 hexadecimal numbers.
/302/206 becomes 0xC286
/302/240 becomes 0xC2A0

Step 3: Check Unicode (UTF-16)
There are many tables and automatic converters from hex to unicode. You can always plug the values into wolframalpha as U+XXXX where XXXX is your hexadecimal number.
In both of these cases, …

Labdabeta 182 Posting Pro in Training Featured Poster

Your problem is that you are printing the number of semicolons (which is the correct name for 'dotcoma', its like a colon (':') but only half ';')

The line in question is

printf("Row %d: %f\n", j+1, (float)dotcoma[j]);

The issue here is three-fold.
1: j is uninitialized, some compilers will set j as 0, others as garbage, either way, its not what you want.
2: you cast dotcoma[j] to a float, this works but is terribly silly.
3: this line is not in a loop.

The solution will have to look something like this:

for (j= (|Insert start value here!|); j< (|Insert end value here!|); ++j)
    printf("Row %d: %d\n", j+1, dotcoma[j]);

Other than that, I would recommend consistent comparisons, either use c=='x' or 'x'==c but please don't switch between the two.

Labdabeta 182 Posting Pro in Training Featured Poster

The issue with sublime, as with notepad++ etc, is that they only do existing languages, not languages that my prof's invent to help us learn specific algorithms and techniques. On top of that, I have never been a fan of autofill (I had to disable it in C::B).

The benefit to using languages invented by prof's is that they always come with a complete BNF description, so it is really easy to write parsers for them (we did an example writing an HTML highlighter). I remember reading somewhere that you can create a specific type of xml document to get C::B or notepad++ to do custom highlighting, but couldn't find an example anywhere.

I think I am going to duplicate this post in a couple of dedicated vim forums as well, to increase my chance of getting a result.

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I used to use Code::blocks and eclipse for code editing, but started to find them slow. I started searching for lightweight IDE's and found that the prevailing opinion is that if you are looking for lightweight code creation you should use vim/emacs, gcc and the other gnu utilities.

I started doing this on my linux box and found it wonderful. Then I sat down in front of my windows computer, installed the core utils, created a custom cmd with batch and installed vim for windows.

My cmd:

@echo off

rem Set the title
title LABinux

rem Set the text colour (this is yellow on black)
color 0E

rem Load into a cleaner directory
cd /d D:\LNX

rem Set console width to 81 characters, height to 80
mode 81,80

cls

:getcmd
rem Set the prompt to current directory> treating D:\LNX as ~
set /p cmd="%cd:D:\LNX=~%> "
rem Call the entered command
call %cmd%

rem Padding between lines
echo.
goto getcmd

I am very happy with my setup (despite the fact that HJKL for movement on dvorak is painful!) but there is a problem with it that is bugging me.

My problem is that vim doesn't highlight some of the languages I use very effectively. For example WLPP (a custom language used occasionally by the University of Waterloo) is highlighted horrendously by default in vim. Some esoteric languages and other less-known languages are also poorly highlighted.

I have seen some tutorials on making vim highlight c++ better, but …

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have an issue with a plain TeX document I am writing. I need to compile drawings as well as images into pdfs. I know how to get images into a pdf using \pdfximage which works if I compile with pdfTeX. I also know how to get drawings into a pdf using TeXdraw and compiling first with TeX into a dvi file, then converting the dvi file to a pdf file (since dvi files support PostScript).

Unfortunately these solutions don't combine in any way. Of course I could draw the diagram I want in a picture, but it is not always the easiest solution.

Is there a way to draw lines/circles/etc in plain TeX without using PostScript?

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have a USB key on which I do all of my programming. It is formatted as an NTFS drive with 32 gigabytes of space.

On this drive I have large C::B projects which contain both windows and linux executables.

When I try to run the linux executables it gives me a permission denied error.

I tried right-clicking on the USB name on the left of the default Ubuntu file viewer and setting 'Allow executing file as program' but it wouldn't hold. Then I tried running sudo chmod -R a+x media/USBKeyName, it took a few seconds to run, but when I checked the file permissions they had been reset. When I look at the checkbox for 'Allow executing file as program' it is highlighted with a minus sign in it.

How can I set the executable bit on my USB key?

Labdabeta 182 Posting Pro in Training Featured Poster

In java, x<<y shifts x y bits to the left. x>>y arithmetically shifts x y bits to the right. x>>>y logically shifts x y bits to the right.

These operations are invaluable when you need to manipulate individual bits of a value.

For example, lets say you are using a bitmask to store 10 booleans in one integer. You can use | (or) to 'set' a bit, & (and) to 'clear' a bit, and ^ (xor) to swap a bit. However, to actually use these operations you would want to have access to the bits. You could do this manually: x|0x10 to set bits 2 and 4. However, bitshift operators let you do this generically: x|(1<<2)|(1<<4) also sets bits 2 and 4. As you can tell, the second version lends itself very nicely to being put into a method, while the first version does not.

There are many more uses of the shift operators in some advanced algorithms, since many of them use the fact that any number has a binary representation to decompose the number into its components (by stripping 1's and bitshifting right). For example you can fairly quickly calculate the remainder of a number by using the method of squaring.

Labdabeta 182 Posting Pro in Training Featured Poster

You are right, but the shift is necessary to get the bytes in place (unless I use a union).

I figured out the problem. When I encounter a negative number, it is stored in the character as, for example, 0xFF (-1). However, when it is implicitly casted to int, it doesn't retain the value of 0xFF, but rather 0xFFFFFFFF (-1) because of C++'s smart casting system. Using an unsigned char resolved the issue.

Thank you for the help though.

Labdabeta 182 Posting Pro in Training Featured Poster

So, all you have to do is to read 4 bytes then reverse them.

Which is exactly what I was doing with my char shifts, and it works about 90% of the time... what makes no sense however is why it fails 10% of the time. The first code I posted should work, but doesn't. I can't figure out why.

write out the file as plain text

Sadly this will not work, my program will not be the only one creating the files, and other assemblers already use binary formatting.

Labdabeta 182 Posting Pro in Training Featured Poster

The file is written by another program of mine (its assembled machine language, this program is an emulator of a CPU). I know for a fact that I want Byte1, then Byte2, etc... when I open the file with HxD it looks perfect, but when I open it as above it gets reversed. This is fixed if I extract it byte-by-byte, but then I run into the issue of occasionally getting incorrect bytes. I tried casting the char to an int for the shifts, but it didnt help. I don't understand why my algorithm wouldn't work.

Labdabeta 182 Posting Pro in Training Featured Poster

The reason I used character shifting is because that is the only way for me to ensure correct endian-ness. When I do it your way I get everything inverted, which isn't helpful. Here is the code you are talking about:

#include <iostream>
#include <fstream>
#include <vector>
#include <cstdint>
using namespace std;
int main(int argc, char *argv[])
{
    if (argc!=2)
    {
        cout<<"Invalid argument count, please provide a file name."<<endl;
        return 0;
    }
    fstream file(argv[1],ios_base::binary|ios_base::in);
    vector<int32_t> data;
    int32_t tmp;
    while (!file.eof())
    {
        file.read((char*)&tmp,sizeof(tmp));
        data.push_back(tmp);
    }
    for (size_t i=0; i<data.size(); ++i)
        cout<<hex<<data[i]<<endl;
    return 0;
}

And given the same input file, it printed:

ffff0e6a
2000c8a
c05c
7000000
1000e8e
e4a
a10
ffff0e8e
e6f
e8f
1000e4f
a10
a10

Which is correct except for being reversed endian-wise and duplicating the last element.

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have a bug in my program somewhere and I cannot understand why. The program merely prints data from a binary file. Here is the code:

#include <iostream>
#include <fstream>
#include <vector>
#include <cstdint>
using namespace std;
int main(int argc, char *argv[])
{
    if (argc!=2)
    {
        cout<<"Invalid argument count, please provide a file name."<<endl;
        return 0;
    }
    fstream file(argv[1],ios_base::binary|ios_base::in);
    vector<int32_t> data;
    int32_t tmp;
    char buf;
    while (!file.eof())
    {//complicated i/o to ignore endianness
        file.read(&buf,1);
        tmp=buf<<24;
        file.read(&buf,1);
        tmp|=buf<<16;
        file.read(&buf,1);
        tmp|=buf<<8;
        file.read(&buf,1);
        tmp|=buf;
        data.push_back(tmp);
    }
    for (size_t i=0; i<data.size(); ++i)
        cout<<hex<<data[i]<<endl;
    return 0;
}

Most of the time it works fine. However, sometimes it gives the wrong output. For example, when my test file contained (as read by a hex editor):

6A0EFFFF 
8A0C0002 
5CC00000 
00000007 
8E0E0001 
4A0E0000 
100A0000 
8E0EFFFF 
6F0E0000 
8F0E0000 
4F0E0001 
100A0000

The program spat out:

ffffffff
8a0c0002
ffc00000
7
8e0e0001
4a0e0000
100a0000
ffffffff
6f0e0000
8f0e0000
4f0e0001
100a0000
0

Why is this?

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have learnt a few assembly languages (MIPS/x86/ARM/MIX) and I have a question about the call stack. Each of those languages uses a different method for subroutine linkage, and the way I learnt them was not conducive to recursion. Granted, if I continue reading my copy of The Art of Computer Programming Knuth claims that he will explain how to do it, however the way he writes I will have to understand everything before that point which will be awhile. I am impatient.

As such I would like to know, in a generic language, how does one implement proper subroutine linkage? So far I have pseudo-code like this:

;To call a subroutine
[FP++]=PC+2;        Push PC+2, (could be FP-- if stack grows negatively)
SP=FP;              Update the stack pointer
PC=Function Address;Call the subroutine

;In the subroutine:
;To allocate a local variable
[SP++]=R1;          Save R1, so it can be used as a local
;To reference it
[FP+1]=R1;          Should be the same as above
;To return
R1=[SP--];          Load R1 and update stack pointer
PC=[--FP];          I think this is a mistake, because now FP is ruined for the calling function?

My question is how do you set the frame pointer to what it was in the calling function when you return? Especially since wikipedia seems to say that even before the frame pointer will be the function arguments, it seems like it would be impossible to maintain the frame pointer.

Labdabeta 182 Posting Pro in Training Featured Poster

I knew I was forgetting a step. I do recall lexers and lexemes. Once I have the tokens, each one acts as a terminal in the context free grammar. Then I just create the derivation tree of the grammar and it should be identical to the syntax tree I am trying to create.

Thank you!

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I recently took a course on assembler/compiler construction. In it we covered parsing algorithms such as LL(n), LR(n), LALR(n), and SLR(n).

I understand how these parsing algorithms can be used to determine if an input string follows a context free grammar (CFG). At some point I also understood how to tokenize the string using the grammar, however my assignment code is not commented (in hindsight that was a mistake) and I do not understand it anymore.

Now I am in need of a parser to convert lines of code into useful tokens and cannot for the life of me remember how to use a parsing algorithm and a context free grammar to do lexical analysis on a string to extract tokens.

How can I take a generic CFG (with accompanying deterministic finite automaton) and an input string to generate an array of tokens?

Labdabeta 182 Posting Pro in Training Featured Poster

Let me take a look at the exact code that you used (just from creation of the time_t to the call of localtime_s) I'll see if I can figure out what went wrong.

Labdabeta 182 Posting Pro in Training Featured Poster

The issue is that localtime and localtime_s are slightly different. The _s stands for safe, it is a memory safe version of localtime. As such it does not create it's own tm* to return, rather you have to send it one. The correct code would be:

time_t now = time(0);
tm ltm;
localtime_s(&ltm,&now);
Labdabeta 182 Posting Pro in Training Featured Poster

This is one of those sneaky bugs. Basically it is telling you that if you declare a variable in the for loop, it only lasts as long as the for loop. At first glance it looks like you only ever use 'n' inside your loop. You are wrong. Let me re-write your code with some different whitespace-ing and you will see why:

// loop to generate audio samples
for(int n=0; n < length; n++) //where n is the step |Start of For loop
    int t = n/freq; //t/freq                        |End of For loop


{//random unnecessary block
    value = amp*sin(2*pi*freq*t);
    write_CSV(n, value, fp);
    cout << n << "\t" << value <<"\n";
}

The reason for this is that loops, and if statements, only last for 1 statement (IE: until the first semi-colon). This would make them really hard to use, except that C++ provides Blocks. Basically any time you say {/*code here*/} it takes all of your code and turns it into one statement. This is true of every time you use the curly braces (as far as I know). However functions often still require them (my compiler doesn't, but ideone does).

Thus the fix is simple: move line 22 into the block:

// loop to generate audio samples
for(int n=0; n < length; n++) //where n is the step |Start of For loop
{
int t = n/freq; //t/freq
value = amp*sin(2*pi*freq*t);
write_CSV(n, value, fp);
cout << n << "\t" << value <<"\n";
} //|End of For loop …
ddanbe commented: Fine eye! +15
Ancient Dragon commented: nice explanation +14
Labdabeta 182 Posting Pro in Training Featured Poster

What have you got so far? What libraries are you using for I/O (Win32API/SDL/SFML/etc)?

Typically you will use your I/O library to poll for events, then detect the arrow key events and use them to modify a variable that holds the ship's position. How this is done varies by library, so we will need to know more about what you have already tried in order to help you.

Labdabeta 182 Posting Pro in Training Featured Poster

You need to ensure that all 3 files will be included in your project. You have to set it up so that first samclass.cpp is compiled, creating samclass.o. Then main is compiled. When main compiles and sees samclass.h with undefined functions it will look for the object file and use it.

From your title it looks like you might be using Code::Blocks. If this is the case you should create a project and select Project->Add Files to ensure that all 3 files are accounted for.

Labdabeta 182 Posting Pro in Training Featured Poster

It worked with my compiler and it worked on ideone (http://ideone.com/Gnxc32), but I expect it probably is undefined.

From what I understand of the situation you cannot create a const char pointer without relying on somebody else to clean it up unless it is a string literal or it uses a predefined buffer size (because you could just use char ret[BUFFER_SIZE]).

Labdabeta 182 Posting Pro in Training Featured Poster

I only took a quick glance at your code. However I did notice one likely bug in your program, particularly in the CCalcCorr class. The issue is that everything in the class is private, which means it would be very difficult to actually call anything from it. You probably meant to include public: somewhere. Remember, by default things in a class will always be private.

EDIT:

Also note that your CCalcCorr class could just be a normal function, with everything local instead. This may make it easier to use in your main function.

Just in case you are unfamiliar, your main function must be in the global scope (not wrapped in any class or namespace) and should be either int main() or int main(int argc, char *argv[]).

Labdabeta 182 Posting Pro in Training Featured Poster

It turns out that a deeper look at strcat reveals me to be an idiot. It works by absorbing a buffer and using that, so that the user can be trusted to delete it manually (or suffer the consequences). Without that I would indeed require that the user deal with cleanup or a wrapper class. Thank you for the help anyways.

Labdabeta 182 Posting Pro in Training Featured Poster

The issue is that the project that this is in was created before the C++11 standard, and thus some of the variable names have been claimed as keywords. I temporarily solved the issue like so:

const char *strapp(const char *str, const char *s)
{
    string ret="";
    ret+=str;
    ret+=s;
    return ret.c_str();
}

but that is some significant overkill right there and this function is called inside a loop, so I want it to be efficient. I know that string literals go out of scope at the end of a file, is there no way to emulate that without globals or shared/unique_pointers or wrapper classes?

EDIT: I know it must be possible somehow, since <cstring> includes the strcat() function which does exactly what I want. The issue is that this is old code and sadly used many very poor variable names (strstr being one of them, explicit being another, so no <cstdlib> and no C++11)

Labdabeta 182 Posting Pro in Training Featured Poster

There are quite a few issues with your code... I will go through them one by one.

1) Invalid entry point

void main
{

Is not the correct way to create your main function. The correct way is:

int main()
{
    //code here
}

or

int main(int argc, char *argv[])//or char **argv or char argv[][]
{
    //code here
}

2) Use appropriate data structures.

This will make your code a lot easier to use and read and debug. Instead of having GPA,ID,etc just lying out in the open, you should wrap them up in a nice package, like so:

struct Student //a class would be better, but I feel like you probably haven't learnt about classes yet, no?
{
    string id;
    string year;
    float gpa;
};

3) Use Modularization.

This means breaking your code up into managable bites. What you did (shoving everything into main) is like trying to eat a sandwich in one big bite. Your are going to choke, break it into smaller chunks!

In this case you should create a bunch of helper functions to break up the task into managable segments, like so:

//load a student from the file
Student loadStudent(fstream file)
{
    Student ret;
    file>>ret.id>>ret.year>>ret.gpa;
    return ret;
}

4) Use arrays

I understand if you do not know about dynamic memory allocation yet, but this problem is easiest if you just use a buffer to store your student gpa's so you can calculate the average. …

iamthwee commented: loved the sandwich analogy +14
Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I was recently looking through some of my code and found what I believe to be a memory leak. It is in a function that appends two strings and I am not sure how to resolve it. Here is the function:

const char *strapp(const char *str,const char *s)
{
    int size,strSize,sSize;
    for (strSize=0;str[strSize];++strSize);
    for (sSize=0;s[sSize];++sSize);
    size=strSize+sSize;
    char *ret=new char[size+1];
    for (size_t i=0; i<strSize; ++i)
        ret[i]=str[i];
    for (size_t i=0; i<sSize; ++i)
        ret[strSize+i]=s[i];
    ret[size]=0;
    return ret;
}

Note that this includes a new operator but would leave it up to the untrustworthy user of the function to delete the resulting pointer (which I didn't believe was possible, since it is a const pointer, but apparently it is). I am wondering if there is a way around this without using the <cstring> or <string> libraries (as they are overkill in this situation).

Labdabeta 182 Posting Pro in Training Featured Poster

Ah, thank you both. Memory corruption was indeed the error (although isBuf==4 is the correct check condition because it is preceded by isBuf++ each time). However my ASCIITOLABASM macro caused a bit of overflow on buf.

Thanks again!

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I feel like this is probably something silly, but for some reason if I declare a variable at a certain point in my code, then never use it... it crashes. This is literally what happens:

//... code here
int isBuf=0;//one of my variables
int zeroAddr=0;//<-- another variable I want, but never ever use (yet)
while (!file.eof())//code continues
//...

The above crashes while

//... code here
int isBuf=0;//one of myvariables
//int zeroAddr=0;//<-- another variable I want, but never ever use (yet)
while (!file.eof())//code continues
//...

Works perfectly. I have checked and zeroAddr is used absolutely nowhere else in my code.

From my understanding of C++ this should not be possible... yet its happening. Any insight as to a possible cause?

For reference here is the entire code, its purpose to emulate a custom machine language:

#include "LABASM.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include <vector>
using namespace std;
string getInstructionString(int32_t x)
{
    string ret="";
    int imm=x&0xFFF;
    int type=(x>>20)&0xF;
    int a=(x>>16)&0xF;
    int b=(x>>12)&0xF;
    switch (type)
    {
        case 0:ret+="BEQ ";break;
        case 1:ret+="BNE ";break;
        case 2:ret+="BLT ";break;
        case 3:ret+="JMP ";break;
        case 4:ret+="MOV ";break;
        case 5:ret+="LDA ";break;
        case 6:ret+="STA ";break;
        case 7:ret+="STR ";break;
        case 8:ret+="INR ";break;
        case 9:ret+="OUT ";break;
        case 10:ret+="JBY ";break;
        case 11:ret+="NAN ";break;
        case 12:ret+="ADD ";break;
        case 13:ret+="MUL ";break;
        case 14:ret+="DIV ";break;
        case 15:ret+="MOD ";break;
        default:ret+="ERR ";
    }
    switch (a)
    {
        case 0:ret+="R0";break;
        case 1:ret+="R1";break;
        case 2:ret+="R2";break;
        case 3:ret+="R3";break;
        case 4:ret+="R4";break;
        case 5:ret+="R5";break;
        case 6:ret+="R6";break;
        case 7:ret+="R7";break;
        case 8:ret+="R8";break;
        case 9:ret+="R9";break;
        case 10:ret+="RA";break;
        case 11:ret+="RB";break; …
Labdabeta 182 Posting Pro in Training Featured Poster

I suppose you are right. Combined I/O is too difficult to standardize. I am going to have to change my definitons so that I don't require it.

This program is an emulator for a machine language for a tutorial I am working on. Unfortunately it is made by experience and I have the most experience with MIX (from The Art of Computer Programming) which is so outdated that it isn't even a RISC computer. Of course I also know basic MIPS and ARM assembly, so I am familliar with RISC architecture. I believe that this issue was caused by trying to shoehorn the two situations together.

The problem is that I never liked memory-mapped I/O, so I took the I/O systems from MIX and tried to fit them into a modern file system (forgetting that that functionality is provided by OS, no?). This lead to me assuming that I needed OPEN and CLOSE commands, and thus a finite count of streams which can be open at once and a generic stream in the implementation.

Looking back at MIX however, I see that indeed Knuth does not use OPEN or CLOSE capability, but rather defines the IN and OUT commands so that they take as input which device they will be accessing, a much more elegant solution.

I remember that in my course on low-level design we looked at memory-mapped I/O and how it uses flags passed back and forth to not require open/close commands either. I suppose I should have …

Labdabeta 182 Posting Pro in Training Featured Poster

Thanks, a great reply as usual. I just don't understand why we can't do read and write to the standard console. Every OS seems to have some way to do it, but none of them seem to be able to get along (EG: I know windows has Get/SetConsoleCursorPosition to 'go back' and I remember I got something similar working on linux once).

For now is it possible for me to write my own class deriving from iostream that would deal with cin and cout, but act as one stream. My guess would be something like:

class ioconstream:public std::iostream
{// private:
    public:
    template<typename T> ioconstream &operator<<(const T& o){cout<<o;}
    template<typename T> ioconstream &operator>>(T& o){cin>>o;}
}cio;

As for why I want to be able to do this, I think it will keep my code cleaner as I have a situation in which I will have 2 streams of any kind open which will be able to read/write to/from each other. It saves me a lot of work if I can use iostream a,b; instead of fstream fa,fb; sstream sa,sb; enum{FILE,STRING,STD}a,b;.

EDIT: Didn't see Schol-R-LEA's post, but I think I addressed his concerns in the last paragraph. However for more detail, I am implementing an emulator for an educational machine language. It allows opening of two streams which can point to either STDIO, the file space or a string manipulation space. I believe that finding a way to shoehorn all three streams into two stream variables would make my code much simpler. …

Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

Looking at the standard streams provided by the stl libraries, it seems as though it is impossible to have 1 stream to use for both standard console IO and file/string IO. However, before I give up I would like to ask, is this possible:

generic_stream stream;
stream=cin;
//now I can use stream as cin
stream>>value;
stream=fstream("myFile.txt");
//now stream acts as a stream to myFile...
value>>stream;
stream=sstream("123 test");

From what it looks like, since fstreams use input and output they derive iostream, which in turn derives istream, which in turn derives ios. However cout uses ostream instead of istream and therefore its common ancestor with fstreams would be ios. But it doesn't look like ios has any actual IO functionality. Does this mean I am SOL? If there is no way using the STLs is it maybe possible using the old c libraries (can a FILE point to standard console IO)?

Labdabeta 182 Posting Pro in Training Featured Poster

Sorry about the late post, it took me forever to test your code with my modifications due to a few sneaky bugs (a dropped compiler and missing breaks were the two big ones). However it seems to work perfectly.

Thank you very much.

Labdabeta 182 Posting Pro in Training Featured Poster

It occurs to me that the only reason I am using threads instead of a sequential programming is that I was under the impression that that was the only way to get code to continue running when its host window was not active. However, from a quick google search most people claim this is not the case.

As such I tried writing a simple program that just switched from red to black. When I tested this program it worked right up until I selected another window, at which point it effectively 'paused' until I selected it again. Is there any way to make this not happen?

Labdabeta 182 Posting Pro in Training Featured Poster

I checked against all of those conditions and here is what I found:

  1. I am not sure how to check the clipping area, but my window is definitely larger than the pixel I am checking (by at least 200 pixels according to photoshop).

  2. How can I tell if a device supports GetPixel? Anyway I have an older version of the same code that works fine on the same exact window...

  3. I read about that issue elsewhere as well, so I added:

    HDC myDC=CreateCompatibleDC(GetDC(myWindow));
    SelectObject(myDC,CreateCompatibleBitmap(GetDC(myWindow),1,1));

And used the new DC handle with the bitmap selected. This still did not work.

As for the multithreading, I am using it so that my program can run while it is in the background (as it will always be since it constantly forces myWindow to be in the foreground). I tested it with that code commented out and calling the thread as a normal function, but GetPixel is still returning CLR_INVALID.

The only differences between the code that works and the code I am using now are:

1) The old code only used <iostream> whereas the new code uses SDL
2) The old code checked a bunch of pixels whereas the new code only checks one (thus the reason I rewrote the code - optimization)
3) The old code also used SendInput to send inputs to the monitored window whereas the new code merely monitors it.

Basically here is the description of what I want my program to do:

  1. Create a …
Labdabeta 182 Posting Pro in Training Featured Poster

Hello,

I have a HWND for a window. I have double checked that it is a 100% valid window by using SetActiveWindow(), SetFocus(), and SetForegroundWindow() on it, successfully bringing it to the frontmost window. However whenever I try to use GetPixel on it it returns -1 (0xFFFFFFFF). What am I doing wrong? Here is a sample of what I am talking about:

HWND myWindow=FindWindow(NULL,"Test Window");
if (!myWindow)return;
SetActiveWindow(myWindow);
SetFocus(myWindow);
SetForegroundWindow(myWindow);
//now the window with title text "Test Window" is active, focussed and in the foreground
uint32_t pxl=GetPixel(GetDC(myWindow),500,500);
//pxl ALWAYS equals 0xFFFFFFFF here... why?!

I have used pretty much identical code before without this problem, why am I getting it now?

The only difference I can see is that this time the x and y coordinates are stored in a global variable for ease of use with my multi-threaded functions (threaded with CreateThread). Can anybody tell me why I can't seem to access the pixels of my window?

Labdabeta 182 Posting Pro in Training Featured Poster

Exactly what I was looking for. Thank you.