deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Moved to code snippets. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

While I'd start by suggesting that you use the .NET file stream options instead, String^ can be converted to std::string using marshal_as if so needed.

Nether_1 commented: This worked, I posted the new code. BTW, I know you can use .NET file stream, but since I'm more acquainted with the fstream system, I used it. +1
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

From the provided code, I can't offer more than

int delete_list_entry(temp_head, randvar);

should be

delete_list_entry(temp_head, randvar);

I get the impression there's a little confusion between how to declare/define functions and how to call them.

Also, if delete_list_entry returns a value, I'd also ask why you're ignoring it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

p is a pointer to read-only memory. While some compilers might allow it to be modified, technically what you're doing is undefined behavior. Change line 6 to char p[] = "foo"; and it should work just fine.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I’ve realized that I’m a little weak when it comes to fix, modify and understand code within large applications, and, needless to say, I need to find a way to get better at it.

There are two books I rather like: Code Reading and Code Quality. They go beyond the how to code beginner books and take a higher level view using examples from large open source projects.

I feel like I’m lacking ‘something’, perhaps just experience…

Yeah, that's it exactly. Understanding the features of the language and how to use them is the bare minimum for functioning as a developer. The real challenge is noodling over and solving problems in an efficient manner. And by "efficient" I don't mean runtime execution, I mean developing a viable solution in a reasonable amount of time. While hobbyists can take all the time they want to make things "perfect", pros don't have that luxury.

Unfortunately, experience is a mountain of mistakes, and there's no shortcut. I'd recommend three things to get started:

  1. Carefully review the established code at your company and try to understand the reasoning behind it. If you have questions, you now have resources in the form of the more experienced developers at the company and perhaps even the original authors of the code.

  2. Understand the business and general business concerns when it comes to custom software. Developers are not an island, and it pains me when new devs come in expecting …

Gribouillis commented: Many great suggestions in this answer! +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm surprised that nobody has even mentioned the TextFieldParser class in Microsoft.VisualBasic.FileIO... :P

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Okay.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What have you done so far? Nobody here will write this for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm a bit surprised you haven't been walking around town handing them out as advertising. There were still a number of big boxes full of shirts after that night, IIRC. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Teaching Pascal as a first language in 2017? Really?

Pascal has the benefit of being very easy to understand. It's also hand-holdey, which for most of us translates to "heavily restricted", but for beginners means less working around the quirks of the language and focusing directly on solving the problem at hand.

Hopefully this is just a kooky bad idea, but with pure motives.

I don't disagree with the concept, but Brain#### wouldn't be a good language choice. From the goal stated in the OP, I'd actually recommend some variant of Forth. Also a legit language (with more practical use than Brain####), and the stack-based design is enough of a difference from your more usual languages to entertain and challenge both the remedial and advanced students.

Another option would be a variant of Lisp, but I think Forth is more accessible.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is clearly a homework or interview question, so please let us know what your thoughts are first.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

char array's are actually pointers

This is a common misconception. An array is not a pointer, but when used in value context, the name of an array is converted to a pointer to the first element in the array. In object context, the name of an array is not converted, such as as an operand to the sizeof operator.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is there any pattern to find out garbage value????????

The term "garbage" is meaningless without context. What's garbage for one program could be perfectly valid for another program. So step 1 is to clearly and unambiguously define what garbage means to your program. Once that's done, you can absolutely create a pattern matcher to detect legit values and everything else is garbage.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Most common domain applications, perhaps? Which examples are you referring to? Bucket sort is certainly not limited to that range, though I can imagine how it's wildly useful.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Step 1 of troubleshooting is narrowing down the places you need to look. With that in mind, my first question would be whether dt actually contains data or not when you look at it in a debug trace.

If it does, then binding or refreshing the grid would be my next point of tracing. If it doesn't, that's your problem. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

zachattack05 : 25 % 2 would return 5

I'm so tempted to write a proof where this actually happens. :D

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

... or use bitwise operator if(i&1) if true even else odd.

I suppose if you want readers of your code to think you're clever, or have legitimately profiled the code for performance, run all practical test cases, and determined that this micro-optimization is warranted and not actively harmful.

Its faster because compare one bit only without mathematics

Citation needed. Compilers are rather smart, often smarter than the programmers who merely think they're smart. Optimizing x % 2 into the suitably fast machine code is rather trivial. If you're applying this optimization with expectations of any noticeable positive impact, I think you'll be disappointed.

In fact, trying to outsmart the compiler can indeed produce slower machine code by bypassing superior optimizations. If it does improve performance for your test cases, there's a good chance the compiler explicitly chose not to optimize it because the results would be flat out wrong.

But let's not quibble over minutia. Instead, how about looking at a far more sinister problem with your suggestion: x & 1 is not synonymous with x % 2. On top of limiting the supported type to integers, the result of the operation varies between the two when working with signed integers. Will it work? Probably...but are you sure? Note that the OP's code is performing this check on values contained in an array. These values will likely eventually be uncontrolled user input. Are you still sure it will work correctly? Can you prove it?

It's unfortunate …

ddanbe commented: Good point. +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Well, assuming the title of your thread is the problem, I'd ask what a.FileName is and contains. An empty string is indeed not a legal file path, so you want to make sure that a.FileName represents a valid file that exists.

Most likely there's a flaw in the UI's design that allows the posted code to run before the filename was properly set and sanitized.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Thus c_str() isn't making a copy of anything, globalPtr is pointing to the same array of characters that abc uses and if you make a change using globalPtr or abc, both are affected.

Yup, c_str isn't required to make a copy of anything, and usually doesn't.

returnValue seems to point to I'm not sure where, but clearly it's not pointing to whatever c_str() returned?

returnValue points to the internal buffer of the string object. VS2015's string class maintains a null terminator in the internal buffer to facilitate simple logic for c_str. The destructor also shrinks the string to zero length, which leaves the released memory clean and explains why the output is "" rather than the previous contents of the string.

I'd suspect GCC "works" because it doesn't have this cleaning step, so whatever was at that memory location remains the same while it "fails" with VS2015 because of the truncation in the destructor. Regardless of compiler quirks, the code exhibits undefined behavior due to accessing memory you don't own.

So, calling c_str() is perfectly fine?

Yes.

if temporary object won't exist after enclosing braces of fun(), then callingc_str() should also be wrong. Isn't it?

It would be if the braces of fun() were the sequence point I mentioned. Instead it's the full expression of returnValue = fun().c_str(). When the initialization of returnValue is complete, the temporary is destroyed, not before.

Secondly, when exactly the temporray object be destroyed?

The …

AssertNull commented: Good explanation +6
nitin1 commented: Awesome :) +4
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Let's start by fixing things so the code doesn't break massively from out of range errors:

#include <iostream>
#include <string>

using namespace std;

typedef int* intPtr;

const int MAX = 100;

void printArray(intPtr total, int size)
{
    for (int i = 0; i < size; i++)
        cout << *(total + i);
}

void addInteger(intPtr intArray, int size1, intPtr intArray2, int size2)
{
    int *p = intArray;
    int *q = intArray2;

    intPtr total = new int[MAX];

    int i = 0;

    int sum = 0;
    int carried = 0;

    while (p != intArray + size1 || q != intArray2 + size2)
    {
        *(total + i) = *p + *q + carried;

        if (*(total + i) > 9)
        {
            *(total + i) %= 10;
            carried = 1;
        }
        else
            carried = 0;

        i++;
        p++;
        q++;
    }

    printArray(total, i);
}

void stringtoInt(string& s1, string& s2)
{
    int size1 = s1.size();
    int size2 = s2.size();

    int i;
    int k;

    intPtr intArray;
    intPtr intArray2;

    intArray = new int[size1];
    intArray2 = new int[size2];

    for (i = 0; i < size1; i++)
    {
        intArray[i] = s1[i];
    }

    for (k = 0; k < size2; k++)
    {
        intArray2[k] = s2[k];
    }

    addInteger(intArray, i, intArray2, k);
}

int main()
{
    string a = "123", b = "456";

    stringtoInt(a, b);
}

The biggest problems were leftover C-style string stuff from my example when you seem to have gone with the consistent approach, and the loop in addInteger used a nonsensical comparison for finding the end of the array. You were comparing …

ddanbe commented: Great answer. +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

while (*p != '\0' || *q != '\0')

This is a red flag. Your arrays are not constructed as C-style strings, so '\0' isn't likely to exist within your owned memory. You can make that happen by adding the terminating value at the end of the arrays:

 intArray = new int[size1 + 1];
 intArray2 = new int[size2 + 1];
 int i;

 for (i = 0; i < size1; i++)
 {
       intArray[i] = s1[i] - '0';
 }

 intArray[i] = '\0';

 for (i = 0; i < size2; i++)
 {
       intArray2[i] = s1[i] - '0';
 }

 intArray2[i] = '\0';

However, that's confusing and smidge wasteful. I'd favor passing the current length of the array to your subsequent functions rather than trying to mix and match an integer array and C-style string rules. It makes your function definitions more complicated, but it's conceptually consistent, and that's usually a win.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

when fun() returns, it calls the copy constructor again, right?

Ehh, kind of. Return value optimization is a thing, but conceptually it's okay to think of things that way for simplicity.

But, won't it call the copy constructor and then make the copy of the object and return it to the returnValue variable?

Yes, but the lifetime of that temporary object ends after the enclosing expression's sequence point. The enclosing expression is your initialization statement for returnValue, which is why you can call c_str successfully (ie. the temporary object still exists), but the pointer is dangling at the end of the statement (where the temporary is destroyed), because it points into the temporary object's memory rather than directly owning the memory.

Boiled down, the problem is really no different from returning a pointer to a local variable even though throwing unnamed temporaries into the mix makes it harder to recognize.

nitin1 commented: +1 +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Can you please explain the reason behind this?

You're capturing a direct pointer to the internal storage of the string returned by fun(), which is a temporary object. The temporary object is subsequently deconstructed, and the internal storage goes away. I'd suggest stepping into everything in the debugger to see how your compiler is handling the objects, because this is correct behavior.

returnValue2 works fine as you're copying the temporary object and preserving its contents in a new object.

nitin1 commented: +1 for to-the-point answer +4
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I know that Daniweb owns the I.P.

No. That was unfortunate wording in previous terms of service, and the intention was to absolve Daniweb of legal responsibility for storing and editing the content of posts. After a quick reading, it looks like the wording was changed.

I want it to be clear that students etc are free to use or adapt it legally for personal educational purposes or some such.

I'm a fan of public domain. Something like unlicense would be sufficient to put code out there in an unrestricted way while also protecting the authors.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'd strongly recommend walking through your code with a debugger. And my big hint for the problem is that the Enter key places a character in the input stream: '\n'. When you mix formatted and unformatted input (eg. getline and the >> operator), there's a strong chance that newlines are being mishandled.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I know that the max value for short data type is 32767

Not necessarily. The C++ standard defines a minimum required range, but compilers are free to make it larger.

but the question is from where we get this number -25536 ?

First I'll note that it's not safe to rely on this behavior. The answer is that your implementation treats signed overflow as wrap-around. Values beyond the maximum positive range wrap around into the negative range.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's not necessary, but generally recommended for classes that implement IDisposable.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Well, for starters the "/ ... /" comment supports multi-line, so you'll need to consider that in your parsing. A simple approach would be a loop that reads and throws away characters until the closing token is found:

    public static void processInput(StreamReader input, StreamWriter output)
    {
        int ch;

        while (!input.EndOfStream)
        {
            ch = input.Read();

            if (ch == '/' && input.Peek() == '*')
            {
                neglectComment(input);
            }
            else
            {
                output.Write((char)ch);
            }
        }
    }

    public static void neglectComment(StreamReader input)
    {
        input.Read(); // Extract the peeked asterisk

        while (!input.EndOfStream && input.Read() != '*' && input.Peek() != '/')
            ;

        input.Read(); // Extract the peeked slash
    }

    static void Main()
    {
        using (var input = new StreamReader(Define_input_output.inFile))
        {
            using (var output = new StreamWriter(Define_input_output.outFile))
            {
                processInput(input, output);
            }
        }
    }

Though this somewhat depends on your future plans for this application. It might be better to perform a proper parsing of the code, though that's quite a bit more work.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'll make the obligatory comment that you should be using a modern compiler rather than trying to kludge a 30 year old compiler into your modern OS.

That said, the message suggests this AKKI wrapper is expecting some sort of input. I'd start by reading the documentation to learn how to use it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The first thing that comes to mind is to filter out the special value(s): MyList.Where(x => !double.IsNaN(x)).Min().

Though depending on what might be acceptable insertions into the list, you might need to consider things like NegativeInfinity as well.

ddanbe commented: kudos! +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The calculations are unnecessary. mktime can be used to normalize the contents of a tm structure to the correct date and time after manual modifications.

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    time_t now = time(0);
    tm *date = localtime(&now);

    --date->tm_mday; // Move back one day
    mktime(date); // Normalize

    cout << asctime(date) << '\n';
}
AssertNull commented: I like this approach. +5
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The inline keyword isn't a guarantee, it's a hint. If the compiler determines that inlining would produce worse code, it doesn't honor the hint. Some compilers just straight up reject the inline hint if there's a loop or troublesome lookup (ie. switch).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You could try not running software that's older than most of the people using it...

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What I DON'T understand is why srand(time(NULL)) and rand, which is what we're all taught to use, are such lousy random number generators

Probably for the same reason gets and atoi are so lousy. The interface was simple, they were "good enough" at the time, and time/experience changes what's considered acceptable in a library.

With random numbers, I'm not.

#include <random> is a move in the right direction, though I'd argue it's not "simple" due to a wide range of needs from an RNG and a bit of design by committee.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You mean issues with different machine word size?

Byte order would be a larger concern. In your case, I'd favor serializing to JSON for your packet.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You still haven't mentioned the use case, so I can only speculate. However, it sounds very much like a binary serialization isn't what you want because there are compatiblity and portability concerns.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I have a lot of classes I need to add a ToByteArray() method to

What's the purpose of this method? Typically I'd suggest utilizing the serialization classes already present in .NET:

public static class BinaryWrapper
{
    public static byte[] Serialize<T>(T obj)
    {
        using (var stream = new MemoryStream())
        {
            var formatter = new BinaryFormatter();

            formatter.Serialize(stream, obj);
            stream.Flush();
            stream.Position = 0;

            return stream.ToArray();
        }
    }

    public static T Deserialize<T>(byte[] b)
    {
        using (var stream = new MemoryStream(b))
        {
            var formatter = new BinaryFormatter();

            stream.Seek(0, SeekOrigin.Begin);

            return (T)formatter.Deserialize(stream);
        }
    }
}

However, it somewhat depends on your use case whether this meets your needs.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I agree with AssertNull, it's very likely the newline character mucking things up. Your compiler (or compiler settings) probably aren't zeroing out local variables while AssertNull's is, which explains the code working in one place but not another. You can verify this by initializing _artichoke, _beet, and _carrot to 0.

Typically, it's not wise to mix formatted and unformatted input (ie. getchar and scanf) due to differences in handling of whitespace. IIRC, the %d format modifier should skip whitespace before attempting a character extract, though I don't recall if that's a hard requirement or just something that a lot of compilers do (it's been a while since I read the standard ;p). You can force it by putting a leading space in your format string:

scanf(" %d", &_artichoke);

fseek(stdin,0,SEEK_END);

Yeah, that's not guaranteed to work. There's not a complete standard way to "flush" stdin in C; the best you can get is some variation of this:

int c;

do
{
    c = getchar();
} while (c != '\n' && c != EOF);

It's perfectly functional, provided the stream is not currently empty. If it is empty, getchar will block for unnecessary input and there's no standard way to get around that particular issue.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

so maybe you need to write

cpp.sh is an online compiler that you can test your theory with. It takes a few seconds to confirm that this does not work. conio is a non-standard library, which means not all compilers (most in fact) do not support it. Those that do support it to varying degrees. Finally, expecting an online compiler to support Windows-based console mode transformations is somewhat unreasonable.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just keep pressing the little X a bunch of times in a row until they are all cleared out.

Yeah, clicking the X 300 times with a couple second wait between each popup is a good way to say "you need to log out and never come back". ;) We need a convenient way to mark all messages as read.

diafol commented: I suggested this a long while back. Too painful +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As I recall you should use fseek and ftell to get the file size[...]

That's fine for simple use cases, but it gets troublesome very quickly. For example, large files introduce a hard limit for both getting the size and using it due to fseek and friends working on long int, and malloc dependent on size_t. Then you have concerns about process memory usage by storing the whole file internally. We can go even deeper by considering different encodings which affect your count calculations and how to handle the characters in code.

In general, if your logic starts with "okay, let's read the whole file into memory at once", then the logic is likely flawed. In nearly every case where a file is involved, you can read it in chunks (tokens, lines, records, etc...), and that's a vastly preferred method.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

to determine if it is a number, keyword or an identifier

This is a key statement to me, because it sounds like you're writing a lexer. If that's the case, it's not really as simple as throwing characters into an array (or some variation of *scanf); you need to include some introspective analysis on the characters to properly tokenize elements of the language.

Would you elaborate on the contents of the file and the language definition? That's somewhat important in giving a proper answer to the question. :)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please start by posting your code and pointing out where exactly you're having a problem.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I had much more respect for his "comedy" news than I have for "real" news".

When The Onion reports things and you can't tell the difference between them and "real" news, there's clearly a problem. Journalism these days is more about pushing agendas than informing people.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What is the exact reason that Iphone is more costlier than Andriod phone

If we're being honest, the reason is the Apple logo.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The option to downgrade will go away on its own after one month, IIRC.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

As rubberman mentioned, those typedefs are specified in <stdint.h> (for C) and <cstdint> (for C++). But note that <cstdint> wasn't officially supported by C++ until the C++11 standard, so if you're not compiling against that standard then defining your own or using the Boost library would be options to consider.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But this does not work.If user input invalid value it start looping.

Indeed. When cin fails to make a conversion, it doesn't remove the invalid characters from the stream. So you have two options:

  1. "Flush" the stream (not recommended).
  2. Read a full line of data and then parse it yourself such as with a stringstream so that cin remains clean naturally.

The second option is recommended because it gives you more flexibility, and "flushing" streams can be tricky. However, the flexibility means you want to choose from numerous methods of going about it. I'll get you started with a simple one:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

namespace
{
    template <typename T>
    bool parse_int(string source, T& value)
    {
        istringstream iss(source);

        return !!(iss >> value);
    }
}

int main()
{
    string line;
    int value;

    while (true)
    {
        cout << "Please enter an integer: ";

        if (!getline(cin, line))
        {
            cerr << "Stream error detected!" << endl;

            // Error handling code here
        }
        else if (parse_int(line, value))
        {
            break;
        }
        else
        {
            cout << "Invalid input\n";
        }
    }

    cout << "You entered " << value << '\n';
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In general if you're receiving an error, it's best practice to post the error. However, at a glance I see two potential issues, taking into account that Turbo C++ is an ancient and non-standard compiler:

  1. Case matters. On line 9 you use Int instead of int.
  2. div is in conflict with the standard library. It would be wise to use a different name.

From a logic standpoint, a/b likely won't give you what you want when a and b are both integers. Regardless of assigning the result to float, all precision is lost in the division step. You should at least cast one operand to floating point.