deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yes, of course there's a way to do that. It's pretty straightforward in that you open the file and then read or write the data. However, it does depend somewhat on the format you want for the file.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Do you want the open mode that was passed to the constructor or open member function? Or do you want to know dynamically whether the last operation was a read or a write?

Ultimately, you'd need to maintain a flag providing this information, which could be stored in the fstream object using xalloc/iword/pword, if you so choose. Though a separate variable would be simpler, in my opinion. Just wrap it up in another class and call it good. For example to remember the open mode:

#include <fstream>
#include <ios>
#include <iostream>
#include <string>

using namespace std;

class File {
    ios::open_mode _mode;
    fstream _stream;
public:
    File(const string& filename, ios::openmode mode)
        : _mode(mode), _stream(filename.c_str(), mode)
    {}

    ios::openmode mode() const
    {
        return _mode;
    }

    fstream& get() {
        return _stream;
    }

    operator fstream&()
    {
        return get(); 
    }
};

int main()
{
    File fs("test.txt", ios::in);
    string s;

    while (getline(fs.get(), s)) {
        cout << s << '\n';
    }

    cout << "Opened in read mode: " << (fs.mode() & ios::in ? "YES" : "NO") << '\n';
    cout << "Opened in write mode: " << (fs.mode() & ios::out ? "YES" : "NO") << '\n';
}

Remembering the last operation is a little more tedious because it needs to be updated every time you perform a read or a write, but it's no more difficult.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm guessing you're typing something like "C8" and expecting sound to magically determine that the string corresponds to 4186, which is unreasonable. You need to match the string with the frequency. Here's one option:

struct note { const char *name; int frequency; };
struct note notes[] = {
    {"C2",  65},
    {"Cs2", 69},
    {"D2",  73},
    {"Ds2", 77},
    {"E2",  82},
    /* ... */
    {NULL,   0}
};

/* ... */

for (i = 0; notes[i].name != NULL; i++) {
    if (strcmp(notes[i].name, notein) == 0) {
        sound(notes[i].frequency);
        delay(50);
        nosound();
    }
}

Also keep in mind that sound takes an integer argument, so you can't pass a string and have it do anything meaningful. In fact, I'm surprised it compiles as you have it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please post your code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

1 - why some C++ PRO don't advice me use these code?(making properties)

Because it's awkward (as you've discovered), unnecessary, and a complete solution isn't as good as what you'd get with another language like C#. C++ "pros" do without excessively awkward fluff.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My question is how does the first example work since i haven't used the .Dispose() method

How would that stop the code from working? You've merely failed to release resources, which depending on the resource involved may or may not cause issues down the line.

I m just unsure sometimes when to use using when not.

If a class implements IDisposable, you should either use a using statement, or call the Dispose method when you're done with the object. I include both options even though using should be preferred because there are situations where a using is awkward, and rolling everything up into a try..finally is cleaner.

castajiz_2 commented: ok, tnx +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Compare and contrast:

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

char* toBin(int);

int main(void)
{
    int n;
    char *out;

    printf("\n Enter no : ");
    scanf("%d", &n);

    out = toBin(n);
    printf("\n OUT %s\n", out);
    free(out);

    return 0;
}

char* toBin(int d)
{
    int d1 = d, r = 0, i = 0;
    char *s;

    s = (char*)malloc(200 * sizeof(char));

    while (d1 > 0) {
        r = d1 % 2;
        d1 = d1 / 2;
        s[i] = r + 48;
        i++;
    }

    s[i] = '\0'; /* Always close the string! */
    _strrev(s);
    printf("\n rev  ptr %s", s);

    return s;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Im trying to accomplish to save both aco####s and settings into the same xml like so

Then if you want to continue using XmlSerializer, you should wrap those two classes in a another class, then serialize that one:

class AppSettings
{
    public General GeneralSettings { get; set; }
    public List<Account> Accounts { get; set; }
}

XmlSerializer treats the entire class hierarchy as a single self-contained XML entity, which means the highest level class is your XML root.

iFrolox commented: Oh, thank you! +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Post your current code.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

heres a nice way for build 1 class 100% 'static'

The "static" object must be in scope wherever you use it, which essentially means it must be global (usually not a good idea). Further, you cannot access "static" members through anything except the "static" object. Other objects will have their own copies of the "static" members, which completely defeats the purpose.

I wouldn't recommend that solution in general, and I certainly wouldn't describe it as a static class.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

then what should i do....?

Call malloc in toBin and free the returned pointer in main.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You're returning a reference to a local variable. The local variable gets destroyed, so the reference is dangling. Just return a reference to myStore[row] directly:

template<class V, class I> 
V& Matrix<V,I>::operator()(int row, int column)
{   
    return myStore[row][column];
}

Alternatively you can make a local reference to the row, then return a reference to the column:

template<class V, class I> 
V& Matrix<V,I>::operator()(int row, int column)
{
    Array<V,I>& myArray = myStore[row];    
    return myArray[column];
}

On a side note, you should consider overloading the operator for const objects as well, and return a const reference:

template<class V, class I> 
const V& Matrix<V,I>::operator()(int row, int column) const;
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But as i am returning a pointer s I can't free it before returning it.

The caller has to free it. While the ideal for robustness is to have memory allocated and freed at the same execution level, that's not always practical.

I take a char array[100],Perform operation on it,and then point my pointer to it at the end.

In this case you're returning a pointer to a local object. The local object gets destroyed when the function returns, so the caller gets what's called a dangling pointer--it points to garbage by definition.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Itworks fine for unsigned variables but the signed output is not correct for int or long.

You seem to have missed the part where I stated that overflowing a signed type is undefined behavior. The same method that works for unsigned types is broken on signed types. There's no safe way to do what you want with signed types, which is one reason why the standard library provides macros that tell you the range limits for the implementation.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Step back a moment and consider why you need clrscr or any variations. It's my fairly strong belief that when you start needing to do any non-linear manipulation of the console, you should probably bite the bullet and move to a GUI.

That said, if you're on a Windows system you can write a clrscr (all of the conio library, in fact) that's portable to any Win32 compiler: https://code.google.com/p/c-standard-library/source/browse/src/internal/_sysconio.c. The relevant parts are:

#include <Windows.h>

void clrscr(void)
{
    HANDLE sys_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO info;
    COORD topleft = { 0 };
    DWORD size, written;

    if (!GetConsoleScreenBufferInfo(sys_stdout, &info))
        return;

    size = info.dwSize.X * info.dwSize.Y;

    /* Overwrite the visible buffer with blank spaces */
    FillConsoleOutputCharacter(sys_stdout, ' ', size, topleft, &written);

    /* If the first call succeeded, this one should too */
    GetConsoleScreenBufferInfo(sys_stdout, &info);

    /*
        Fix the character attributes (color, etc...) for the "whitespace"
        if they weren't set to defaults. Otherwise they would be lost.
        Finally, reset the cursor position.
    */
    FillConsoleOutputAttribute(sys_stdout, info.wAttributes, size, topleft, &written);
    SetConsoleCursorPosition(sys_stdout, topleft);
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

However, the values for INT_MIN and INT_MAX are shown in the appendices as being the same as SHRT_MIN and SHRT_MAX repsectively.

The minimum range of int is indeed 16 bits, even though you're unlikely to see less than 32 bits on a modern implementation.

I was hoping that by increasing a "short" variable, for example, to EOF, it would stop within its range. Why is this not occuring?

EOF is a negative quantity that may or may not be -1. What you're actually doing with that code is invoking undefined behavior by overflowing a signed integral type. A safer approach is to use unsigned types instead (since they have defined wraparound behavior), then stop when the value wraps to 0:

unsigned char x = 0;
unsigned short y = 0;
unsigned int z = 0;

while (++x != 0);
while (++y != 0);
while (++z != 0);

printf("Range of unsigned char [0,%u]\n", --x);
printf("Range of unsigned short [0,%u]\n", --y);
printf("Range of unsigned int [0,%u]\n", --z);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please post actual C code that you want to add this feature to. If you're working with a pointer to a string literal then you can't modify it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In my experience, deductions from ignorance don't produce accurate results. No offense to your dad, but my usual response to folks who confidently make shit up is to nod and promptly change the subject.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Is the array holding the string large enough for another character? Because if so it's a simple matter of:

s[size] = c;      // Overwite the nul with a new character
s[++size] = '\0'; // Terminate the string after the new character
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

is the data likely to get damaged in a short period of time(3-4 months since writing let's say) on a flash drive?

Not unless you have low quality hardware. I'd ask your dad to cite his references, because unless there have been multiple peer reviewed studies from reputable sources that conclude "likely" damage in flash drives, I'll simply call bullshit and leave it at that.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

the data on CDs is much more less likely to get distorted/destroyed

That's easy to refute. Grab a CD and scratch it up on either side. You've distorted/destroyed the data with ease. Now do the same thing with a flash drive and see how much harder it is to physically damage.

However, with proper storage, optical media has a much longer shelf life than solid state. This is a direct result of intended usage though. A CD or DVD isn't designed as a pluggable hard drive that should be read from and written to on a regular basis.

I think you're both missing the target a bit, since CD/DVD and memory sticks solve a different problem. They co-exist quite nicely. ;)

flash drives are (very)prone to have information errors because of physical processes?

Not if it's quality hardware. Has your dad been buying the cheapos at the cash register? Those are shit.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster
#include <iostream>
#include <string>
#include <fstream>

int main()
{
    using namespace std;

    const int rows = 4;
    const int cols = 3;

    ifstream file("test.txt");

    if (file.is_open()) {
        float r[rows][cols];

        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                file >> r[i][j];
                file.get(); // Throw away the comma
            }
        }

        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                cout << r[i][j] << ' ';
            }

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

Thanks deceptikon for ur code and Checked it today and it's giving me some error, Can u tell me where I am going wrong

You're probably not using a compiler that supports C++11, or compiling with that switch disabled. However, I can't tell you what's wrong when you don't tell me what the errors are. :rolleyes:

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

And in all reality I will be working with more than two files because I am working on an external polyphase sort

Okay, you're making it too complicated. You'll already have a collection of stream objects for a polyphase sort, so just mark the index of (or have a reference to) the current output stream and update it as necessary. That's so much more intuitive than swapping streams left and right, even if you were using C++11.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Thanks and How to write the file path in program?

...um, you may want to drop back a bit and study file I/O in C++. I had been operating under the assumption that your problem was parsing the format, not the basics of how to read a file.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Define "swap" for your purpose. Do you want to swap the file references entirely or just copy the contents of one stream to another?

Or is there a way to get the name of the file that the fstream has open?

Nope. You need to save the name, which is easy by wrapping the whole shebang into another object that has two members: one for the stream and one for the file name.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

CSV is just a text format, so you'd open and read the file as you would any text file. However, you need to parse the format. For example using a very simple variant of CSV:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    ifstream in("file.csv");
    vector<vector<double>> fields;

    if (in) {
        string line;

        while (getline(in, line)) {
            stringstream sep(line);
            string field;

            fields.push_back(vector<double>());

            while (getline(sep, field, ',')) {
                fields.back().push_back(stod(field));
            }
        }
    }

    for (auto row : fields) {
        for (auto field : row) {
            cout << field << ' ';
        }

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

You're not using the sender parameter, so it can be anything (I'd just use Me). However, you are using the e parameter, so you need to fill out a new GridViewEventArgs object and pass it in:

Protected Sub btnEdit_Click(ByVal sender as Object, ByVal e As System.EventArgs) Handles btnEdit.Click
    Dim editArgs As New GridViewEditEventArgs With {.NewEditIndex = row}

    GridView1_RowEditing(Me, editArgs)
End Sub

In this case, row would be whatever row you want to edit. You may want to use the first selected index, or loop through all selected indices and call the RowEditing handler for each, but that's entirely application specific.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You spelled "asset" wrong, for one thing. For another, I suspect you wanted to use splits in the foreach loop rather than assetClasses.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

that's why someone tell me for learn C# lol

C# has its own quirks that complicate the learning curve, so don't expect any magic by learning a different language. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

im just gooing to leave this interesting article for the apple fans! :)

Hardly interesting. I've seen umpteen articles like that going in every direction, every which way, and always with different lists of features that are the "XYZ killer".

Though I especially enjoyed the mention of screen dimensions (a hardware feature) in a list comparing operating systems. Could the author not find enough legitimate OS features that "beat" iOS to make it a round 10? ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if it has been done for once

How does it know? What if you've created other objects? What if those objects create objects behind the scenes or trigger events that spawn threads that create objects? It's not quite as simple as you seem to think, and you may be misunderstanding how the garbage collector works.

There's plenty of learning material on the .NET garbage collector. Maybe if you point to parts that you don't understand rather than paraphrasing how you think reality should work, it would be easier to help clarify things for you.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If it's .NET, the garbage collector is running. Whether it actually does something is up for debate, but there basically won't be a time when you have to worry about manually managing memory for stuff that the garbage collector handles.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Most of us older folks lived our entire lives without a phone attached to our bodies, so what we never had we never miss.

And you walked 10 miles everywhere...up hill...both ways, and you were thankful for it. ;)

I didn't have a cell phone until my late 20s, but that doesn't make it any less useful to me now.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I think it is 1.79769e+308.

It's implementation defined.

It tells me not to use short.MaxValue so I assumed that numeric_limits::max will do the same as this?

The two are roughly synonymous. I suspect the comment is saying not to use short.MaxValue because short.MaxValue gives you 32767 rather than 32768, which breaks the algorithm.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I intend to switch to a Windows phone when I get tired of my 4S. ;p

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

And would you please tell me how to use the return statements for returning Matrices

Stop using arrays and switch to vectors (or a matrix class), that's how you do it:

vector<vector<int>> func();

There are some things that array types simply aren't suited for, and this is one of them.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The trick is that arrays in C are passed by simulated reference. The syntax you're using obscures it a bit, but these three declarations are functionally identical:

void getmat(int a[50][50],int n);
void getmat(int a[][50],int n);
void getmat(int (*a)[50],int n);

So an array is actually passed as a pointer to the first element, which is how you simulate pass by reference in C. And that's why when you scanf into a[i][j], it actually modifies the original array passed in from main.

The weirdness of arrays in C makes a lot more sense when you have a good handle on pointers.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What will be c++ equivalent of this snippet?

There would be no differences (barring the obvious syntax errors, but that would be broken in both languages). The FILE structure is a standard type inherited from C.

Also, is this struct correct for c++?

Yes.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A slightly simpler explanation is that the arrow operator is syntactic sugar for accessing a member of a pointer to structure or class: p->member is equivalent to (*p).member. Since the latter is awkward to type and it's very common to have a pointer to a structure or class, the arrow operator was introduced as a syntactic convenience.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I know that having the same person appear in the same table more than once is troublesome.

Basically you've described the difference between a normalized and denormalized database. A normalized database stores the actual data in a single table and uses referential links (such as primary keys) to share records. A denormalized database duplicates the data as necessary.

There are pros and cons to each design. Normalized databases are cleaner and easier to reason about, but also more complex and slower due to the linking. Denormalized databases are usually designed that way because query performance is critical. For example, Daniweb's database is partially denormalized.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

3D seems to work best with high frame rate media. Otherwise it's just blurry and distracting. How 3D is utilized in the video is also critical. A lot of the time it's just an after thought gimmic rather than fully integrated into production from the start.

All in all, I'm not a fan, but there have been a handful of decent vids with 3D. Never seen one of the 3D TVs though.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but im not sure how i would fix that one as of now.

Move all declarations to the top of the current scope. For example with your main.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "player.h"
#include "other.h"

int main(int argc, char const *argv[])
{
    dug * one = malloc(sizeof(dug) * 1);
    player * us = malloc(sizeof(player) * 1);
    FILE *sy;

    us->cheat = malloc(sizeof(int)* 1);
    *us->cheat = 0;

    sy = fopen("story.txt", "a");

    us->name = malloc(sizeof(char)* 40);
    us->HP = malloc(sizeof(int)* 1);
    us->dir = malloc(sizeof(int)* 1);
    us->help = malloc(sizeof(int)* 1);

    one->torch = malloc(sizeof(int)* 1);
    *one->torch = 1;

    *us->HP = 10;
    *us->dir = 3;//1 north, 2 east,3 south,4 west
    *us->help = 0;

    one->WIN = malloc(sizeof(int)* 1);
    *one->WIN = 0;

    printf(" What is your name:");
    scanf("%s", us->name);
    fprintf(sy, "The journals of %s\n", us->name);

    RoomOne(us, one, sy);

    if (*one->WIN == 0) {
        printf("Game Over,%s\n", us->name);
        fprintf(sy, "\tLast entry, %s\n", us->name);
        if (*us->cheat == 1) {
            printf("winners never cheat, and cheater's never win.\n");
        }
    }
    if (*one->WIN == 1) {
        printf("You have escaped the dark, Now face the light.\n");
        fprintf(sy, "you have won the game, %s.\n", us->name);
    }

    fclose(sy);
    return 0;
}

Easy peasy. Prior to C99, C doesn't allow declarations to be mixed with executable code; declarations always come first.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Were you perchance compiling as C99 or C++ on Linux? Because Visual Studio doesn't yet support C99's mixing of declarations and executable code unless you compile as C++.

All of your other main.c errors stem from the first error. Once you move all declarations to the top of the scope, that error will go away. You didn't show the commands.c file, so I can't comment on it.

Also note that warning C4996 is bullshit and can be ignored in all cases. Feel free to disable it entirely from the project configuration.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

When you said "did not work", please be specific. I know what happened, but that's only because I can deduce it due to experience. Not everyone may be able to immediately call from memory that opening a file in write mode will truncate the file to 0 bytes. You can open the file in read-write (aka. update) mode to get the correct behavior:

ofstream outfile("test.txt", ios::in | ios::out);

Note that this method only way that works is if you perfectly overwrite what's already there. If the overwriting data is shorter or longer by even a single character, it "doesn't work". ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Think of programming like the martial arts. You can probably learn the basics quickly, but it's not very useful at that level. To reach and maintain a level where it is useful, you have to put in a lot of effort. And anyone who tells you it's easy is trying to sell you something. ;)

<M/> commented: Yup, that's accuarate +8
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

In general, boolean logic precedence rules place NOT first, then AND, then OR. So in your example, it would go like this:

(NOT (X OR Y)) AND Z

Or broken down using temporaries:

A = X OR Y
B = NOT A
C = B AND Z
Q = C
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Would make str str?

I don't understand your question, but if you're asking whether you want to use the strstr function then the answer is yes. strstr will return a pointer to the matched string, or NULL if it wasn't found. So you can repeatedly call strstr and then skip over the match:

char *p = line;
char *match;
int n = 0;

while ((match = strstr(p, key)) != NULL) {
    /* Update the match counter */
    ++n;

    /* Skip over the match so it isn't found again */
    p = match + key_len;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Unless 5+ is closer to 10+ with an outstanding portfolio, you may want to be more realistic. Game development is extremely competitive, and systems development is difficult to get into due to the lack of open positions.

Though I'd wager systems developers are better paid in general.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The answer is 214. All you need to do is recognize that you're working in base 8 rather than base 10.