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

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

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

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

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

... 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

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

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 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

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

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

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

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

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

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

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.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

First and foremost, you don't need to cast the return value of malloc. In fact, doing so can hide legitimate errors such as failing to include <stdlib.h>. Second, sizeof(char) is guaranteed to be 1 in all cases, so things like sizeof(char) * some_int are unnecessarily complex.

I have seen a few different ways of doing malloc error checking? Is one way better than the other?

As for checking the result, both x == NULL and !x will work; it's really a stylistic matter of which one you find more informative.

Are some exit codes better than others?

The only codes guaranteed to be portable are 0, EXIT_SUCCESS, and EXIT_FAILURE. But before you use 0 or EXIT_SUCCESS, keep in mind that both are treated as success codes. Why exit with 0, for example, if the program terminated unsuccessfully?

Is using fprintf with stderr better than using a printf statement?

Yes. printf is forced to stdout, but what if you want your errors to go to a log file rather than standard output along with non-error output? fprintf and similar give you more flexibility in error reporting.

Is using a return instead of an exit better?

Both are pretty awful in general, and it's because terminating on an allocation failure instead of trying to recover is usually not the most robust approach.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Well, I was feeling under-qualified based on what I was seeing out there for available positions.

Job "requirements" lie like a rug more often than not, and the actual requirements tend to be significantly lower. But by demanding the world, it's easier to catch the better talent from the start.

Every time I read a listing that says you must have XYZ, I'm reminded of more than one position in 2000 that required 10 years of Java experience.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What am I missing here?

Two things:

  1. Student s(pName) is creating a variable called s via the const char* constructor of the Student class. I get the impression you're confusing this with a function declaration given your mention of a "variable name".

  2. You can generally add a const qualifier without issue, but it cannot be removed without a cast. This is what the book is explaining. pName does not have a const qualifier, but it can be safely passed to the Student constructor that expects a const qualifier. This qualifier will be added for you automagically and the parameter to the constructor will be treated as const.

The code isn't ideal, of course. pName should be declared as const to avoid subtle issues which could arise depending on how the constructor uses the pointer.

rubberman commented: Good explanation. +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Congratulations! You've found an inconsistency in terms with binary trees. :) There are actually a few of them, but counting levels is a notable one. As James said, each paper or book should be internally consistent, but you'll want to take care to follow the source material carefully. If you use multiple conflicting sources, pick one and convert the calculations of the others as necessary so that your stuff is internally consistent.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how would you do the math with the expression?

Push any operands. On an operator, pop the number of operands required, then push the result. Repeat until there's only a result. For example, 1 + (2 * 4 + 3) would be converted to 1 2 4 * 3 + +. It would be evaluated like so:

  • Push 1 - Stack: {1}
  • Push 2 - Stack: {2,1}
  • Push 4 - Stack: {4,2,1}
  • Pop 4 and 2, multiply them, and push 8 - Stack: {8,1}
  • Push 3 - Stack: {3,8,1}
  • Pop 3 and 8, add them, and push 11 - Stack: {11,1}
  • Pop 11 and 1, add them, and push 12 - Stack: {12}
  • You're done, pop the final result of 12 - Stack: {}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Will the malloc for ptr2 or ptr3 will allocate the same memory that has been freed by free(ptr1)..

Maybe, maybe not. It really depends on the memory manager malloc uses for that specific implementation. I wouldn't make that assumption though.

what will happen internally if I free a memory which is already freed.

Well, given that the block of memory no longer exists as far as the memory manager is concerned, bad things will happen. Officially, you invoke undefined behavior. In practice, you'll be looking at crashes, memory corruption, and potentially an unwanted release of a reused block.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You have a circular reference in your includes. The easiest fix as-is would be to remove the include for LinkedList.hpp in your LinkedNode.hpp header.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how would i need to change this code to accept strings insted integers in avl tree?

Agreed with David W. Though the function seems entirely unnecessary. It's generally better practice to avoid having functions that do multiple things (ie. gather input and insert into a data structure) in favor of just one (ie. only gather input and return it or only insert into a data structure with provided values). Since your class already has an insert method, this function doesn't really do anything to justify a separate function.

It's also inflexible in that it only takes input from cin and also unconditionally writes to cout, so you can't automate this process such as accepting input from a file silently.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm not sure of the rationale behind not allowing VLA (variable length array) initializers

It's a combination of not complicating the compiler and not hiding an extremely volatile runtime task behind benign syntax. Even in C99+, VLAs are risky and not something I'd recommend using. Robust code shouldn't use them, as failure to allocate cannot be recovered from. A solid solution would still use the gamut of VLA, static array, and dynamic array, so cutting out the VLA part would actually simplify code.

you should consider using calloc instead of malloc

I'm torn between saying "no" and "hell no". The problem here is that an array of pointers is being allocated, and calloc encourages a false sense of security that those pointers are initialized to NULL. NULL need not be synonymous with all bits zero, which is what calloc does.

Otherwise, kudos for a good post. You get my upvote. :)

Blake_2 commented: How do I edit my post on here? I see a major typo and I want to include the calloc thing you mentioned; I wasn't aware of that! +0
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It could be the Framework or it could be how it has been implemented by my predecessor

It's the latter, almost surely. The Entity Framework most certainly has its quirks, but being unstable and slow are not among them when used properly.

So I'm wondering if there is a way to just take the entity part out and build an old fashioned data layer with views and stored procedures...

It rather depends on the design, and I suspect the design is fairly entrenched in EF weirdness. My personal preference is to use more of an ADO.NET approach with EF to facilitate database compatibility, but that's not really at issue here. I suspect you're stuck optimizing a poor design. Sorry.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

This is C right?

With any luck it's C++ as best practice in C is to specify void as the parameter list. But yes, there's no termination condition in declaration_list to stop the recursion, so it'll go until the machine says "uncle".

rubberman commented: IE, the stack overflows! +13
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Any reason why you would do it one way over the other?

Three words: don't repeat yourself. Saying if (x == true) is redundant. The context alone tells you that x represents a boolean. If you're being redundant "just in case", then would that be an argument for stuff like this?

if (MyMethod() == true == true)

;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The problems I guess would be navigating from a language with a certain feature to a language without a certain feature

That's one problem, yes. Another would be choosing a consistently compatible translation route when the target language has multiple ways of doing the "same" thing that in practice may not be the same as the source language. Another might be performance concerns of compatible translations where you don't want the obvious translation because it's hideously slow. Security concerns also vary between languages.

All in all, translating a program between languages tends to be far more complex than it initially seems. It requires intimate knowledge of both, and often there are parts you simply cannot convert automatically without some manual intervention to resolve conflicts.

overwraith commented: Good observations. +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

or cracker are going to crack it easier, steal people's data and people will start disregarding software as unsafe.

Here's my take on it: insecure software will be insecure regardless of code availability. Open source certainly makes insecure software easier to crack, but the underlying problem isn't being open source, it's being insecure.

The fix is not to implement security by obscurity and hope crackers aren't smart enough to dig into the binaries, the fix is to correct security holes. And for that goal, open source is potentially superior as there can be more eyes on the code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm probably a glutton for punishment, but are threads just a bit easier to follow now?

thumbsUp.jpg

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think this is an old micro-optimisation thing that is irrelevant with modern compilers.

It was irrelevant even in prehistoric times too, unless you were working with one of the dumbest compilers ever. Even Dennis Ritchie's first C compiler performed this optimization.

However, note that the type of i matters. For int (or any built-in type, generally), the two are functionally identical. For class types that overload the ++ operator, the prefix version will likely be slightly more efficient.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You just said exactly the same thing, with the same non-conventional term. Show me a code example of what you think a "general property" is. Then I'll tell you what the difference is between them and auto properties.

I'd rather not assume what you mean, give a good answer, then have you shoot back immediately that it's not what you wanted.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Actually, in C++, you can use C functions, or C++ stream functions, including doing things like turning off echo in input streams, so you can do the mapping of input characters to things like '*'.

Do tell. Unless something has changed that I'm not yet aware of, this couldn't be done without depending on behavior provided by whatever shell is active.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Try using System.DbNull.Value instead of vbNull. vbNull doesn't represent what you think it represents. ;)

Santanu.Das commented: perfect suggestion +5
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I always thought I had been programming in C++ :/

You have (probably). But it gets interesting when extensions and libraries are thrown into the mix. Here are the high level options:

  • Standard C++: Only uses libraries and features clearly defined by the ISO standard document. It's highly portable, but quite limited.

  • Compiler-dependent C++: Only uses libraries and features supported by the compiler. This often includes standard C++, but also has extensions to the language as well as extra libraries to make your life easier. The potential problem is you're limited to that specific compiler, and sometimes even that version of the compiler.

  • Platform-dependent C++: Uses standard or compiler-dependent C++ coupled with the APIs offered by the operating system. You may or may not be limited to the compiler, depending on what OS libraries it supports, but in general platform-dependent code is more portable than compiler-dependent code.

  • Third party libraries: Any of the above can be used with them, but you're limited by what the library itself supports.

In the case of getch, it's a compiler-dependent function. So while your code might otherwise be standard C++, using a function that isn't defined by the standard document means your code's portability is affected.

However, since the standard is limited, there are things you simply can't do with standard C++. Raw input is one of them. If you need it, you have no choice but to find a non-portable solution. But in those cases, determining how portable you need …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For example, if key 0 contains a vector containing a b c d and key 1 contains a vector containing 1 2 3 4, would there be any way to output a 1 b 2 c 3 d 4, instead of a b c d 1 2 3 4?

std::map doesn't readily support that in an elegant manner. Obviously you could repeatedly iterate through all of the keys, maintain an index to the value, and output the element at that index. But this seems like more of a band-aid born from the wrong data structure choice.

So let's take a step back and figure out exactly what the purpose of this map is. Can you clarify?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is there no such thing for Windows?

It depends on the IDE being used and how it handles program output. I'd be surprised if there weren't an IDE that allows you to display output in a tool window like XCode. Typically you'd have your program open in a new console window for testing, is that not sufficient for your needs?

That said, you can do this with Visual Studio after a fashion.

  1. In VS, navigate to Tools | External Tools.
  2. Click the Add button.
  3. Under the Title field, type something like Console.
  4. Under the Command field, type cmd.exe.
  5. Under the Arguments field, type /c $(TargetPath)
  6. Check the Use Output window option.
  7. Hit OK to save the new tool.

Now Console is available from the Tools menu, and you can add a button to your toolbar that activates it easily to execute your latest build and redirect stdout to the Output window.

There may be an easier way to do this, but I don't know it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Forget that you're dealing with miter->second for a moment. How would you display the contents of a vector? We know cout doesn't have an overloaded << operator for collections, so you're stuck with some variant of a loop. This comes immediately to mind:

for (auto it = v.begin(); it != v.end(); ++it)
{
    cout << *it << ' ';
}

Since this is a vector of vectors, you have a nested loop:

for (auto row = v.begin(); row != v.end(); ++row)
{
    for (auto col = row->begin(); col != row->end(); ++col)
    {
        cout << *col << ' ';
    }

    cout << '\n';
}

Now replace v with miter->second, as that's your reference to the mapped vector object.

The idea here is to start with something you understand, then add complexity until you have the final solution that you're looking for.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

m==textBox1->Text;

Two things:

  1. m is declared as std::string, while the Text property is declared as System::String^. The two types are not directly interchangeable.

  2. == does a comparison, not an assignment.

Also note that m only exists inside the event handler, so if you need it beyond that, it should probably be a private member or something.

ddanbe commented: Your indeed worth, to be called a "Code Sniper" +15