Retrieving data from a file

This is a discussion on Retrieving data from a file within the C++ Programming forums, part of the General Programming Boards category; There's nothing inaccurate or misleading about it O_o Serialization is the process of [...] used in a running program. That's ...

  1. #16
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,282
    There's nothing inaccurate or misleading about it
    O_o

    Serialization is the process of [...] used in a running program.
    That's not serialization. That's a binary dump.

    Serialization is the process, in total, of transforming data for the purposes of storage or transmission.

    Dumping raw binary data and reading that raw binary back into an application omits the only step that makes serialization serialization.

    You can store anything [...] a serialized array of structs.
    This is all true. However, a binary dump of `unsigned int glyph[64][64]' is not the same a PNG which is not the same as a binary dump of `unsigned int glyph[64][64]' in "network byte order".

    and you are welcome to add to it if you think it is incomplete in some way
    It seems to be a closed wiki; so no, I can't.

    IMO unless you are an [...] not require much explanation.
    Serialization itself is extremely simple. It is the motivation that makes the implementation difficult. What are you serializing the data for? The answer determines how much difficulty you'll have serializing your data.

    [Edit]
    And it is an immense topic venturing into virtually all areas of computer science. Just because displaying the in memory integer value `0xdeadbeaf' as... whatever it is counts as serialization doesn't mean that that is the limit.
    [/Edit]

    Soma
    Last edited by phantomotap; 02-25-2010 at 09:15 PM.

  2. #17
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by laserlight View Post
    There are two things that are inaccurate about that definition: the result of the serialisation does not necessarily have to be saved in a file, and the serialisation format does not necessarily have to be "the same form as it is being used in a running program".
    Point taken. I think it does accurately describe a common purpose ("use value") of serialization, and thus should suffice to orient the reader's mind to the idea: most people will intuitively make the connection that data written to a file could just as easily be written to a buffer or transmitted (so maybe "file" is used in a loose sense here). But I will add a couple of words to that effect.

    Vis, "the same form": a completely inclusive definition, and a discussion of all aspects and possibilities, all explicitly listed (no matter how trivial) would obscure the presentation of that "use value". For example, an encyclopaedic dictionary (if you've seen one) is a very interesting thing, but not the first place I go to when I want a clue as to the general use or meaning of a word.

    So it's just "an intro", not the authoritative reference, hopefully that's obvious. It might have been better to include a scenario like kamitsuna is dealing with here instead of/as well as the linked list tangent (which was meant to illustrate the issue with pointers), to further illustrate the use value.

    [...] here you go, replaced with:
    The most basic purpose of serialization is to save or transmit data in a form convenient to the way it is being used. For example, a serialized data file can be read in later and used by the same or another program. Serialized data files are sometimes called "dat" or "bin" files.

    Serialized data files cannot be read as normal text in a file browser or editor, because the typed (ints, structs, etc.) data is not translated into strings.
    Last edited by MK27; 02-25-2010 at 09:28 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #18
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by phantomotap View Post
    Dumping raw binary data and reading that raw binary back into an application omits the only step that makes serialization serialization.
    Well, enlighten me then.

    It seems to be a closed wiki; so no, I can't.
    In fact, it is a cboard undertaking from a few years ago. You have to have a sourceforge account (simple) and then PM Elysia to get editing permissions.

    Just please don't do stuff like this

    [Edit]
    And it is an immense topic venturing into virtually all areas of computer science. Just because displaying the in memory integer value `0xdeadbeaf' as... whatever it is counts as serialization doesn't mean that that is the limit.
    [/Edit]

    You could pave the floor of the seven seas with this and still not be done -- if you get my drift, sometimes less is more. You don't need to address people who already understand serialization with some new and little known facts, and you don't need to sell how wonderful and important it is. You need to quickly and simply show (eg) kamitsuna the why and the how. Once they have that, there are plenty of more in depth and advanced resources they can refer to if interested.
    Last edited by MK27; 02-25-2010 at 09:42 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #19
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,282
    O_o

    Serialized data files cannot be read as normal text in a file browser or editor, because the typed (ints, structs, etc.) data is not translated into strings.
    Unless that happens to be the way the program serializes the data. Human readable serial formats are extremely popular these days. See JSON and XML for major examples.

    So it's just "an intro", not the authoritative reference, hopefully that's obvious.
    The problem is that it makes bad generalizations without providing context or links to additional information. Despite being a simple introduction it may read as potentially authoritative in the eyes of a beginner possibly preventing them from seeking out additional resources or misguiding them in the search for those resources.

    How about ignoring bad generalizations for a good one?

    From raw binary to complex markup, the format of the serialized data depends on the requirements of the application.
    And adding a few links to JSON, XML, and libraries that may make these formats palatable to a beginner.

    And instead of a poor attempt at explaining padding how about links to articles explaining what padding and endianness are and why they may matter.

    Soma

  5. #20
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,282
    You're a fool.

    I can hardly believe that you think that a single poorly phrased, ambiguous, misleading, and incorrect document claiming "Serialization" in the title is sufficient guidance for a beginner, like "kamitsuna", searching for a way to store his RPG character information.

    But then, I've read some of your posts about C++ despite being a newbie so I find I do believe.

    Soma

  6. #21
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Okay, I think I see who you are and where you are coming from better now

    Quote Originally Posted by phantomotap View Post
    Unless that happens to be the way the program serializes the data. Human readable serial formats are extremely popular these days. See JSON and XML for major examples.
    To be honest, this is part of what I meant by "obscurantism": yes, that's true, but what it obscures is the core principle of which you might want to make a beginner aware: that you do not have to translate your data into text in order to store (or transmit) it. It is self-evident that you can use XML to organize and store information, and the first thing most people do when they learn programming and want to save information is they do it in the form they have been presenting it in on the console: as text. I want to present serialization as an alternative to that, so XML just seems like a peculiar tangent of little value at that point.

    A page containing everything everyone can think of about a topic is nearly impossible to put together in a way than doesn't render it a meandering, babylonic mess (some people like doing that, surprise surprise).

    However, I've changed this to:

    "Serialized data files often cannot be read as normal text in a file browser or editor, since the typed (ints, structs, etc) data need not be translated into strings."

    These are the first details of which I think a beginner needs to be aware, free of commentary that will just amount to noise.

    The problem is that it makes bad generalizations without providing context or links to additional information. Despite being a simple introduction it may read as potentially authoritative in the eyes of a beginner possibly preventing them from seeking out additional resources or misguiding them in the search for those resources.
    I don't think anything can be done for a person that hopelessly simple minded -- or rather, I think someone like that would qualify as mentally handicapped (honestly), or very juvenile and hopefully has some more direct guidance in their life (eg: a parent or teacher). When was the last time you googled something, read one thing at random, and decided that was good enough? There is such a thing as "excessively patronizing". Another parallel: you know how legal documents read, because they must be sure to close all loopholes and stand up to lawsuits, etc: they read like obscurantist crap, unless you are a lawyer.

    And adding a few links to JSON, XML, and libraries that may make these formats palatable to a beginner.
    JSON is just a form of AJAX, isn't it? From a C/C++ perspective, programming for that is not a beginner activity. Vis, XML, I would think a separate article, linked to this one, would be better. You add a line like this:

    [[XML]] is a form of text based serialization.

    Save the page, click on XML and you get a new blank page ready to be written. Nb. there are a bunch of other unwritten links in that page.


    And instead of a poor attempt at explaining padding how about links to articles explaining what padding and endianness are and why they may matter.
    Tch. There's no "poor explanation" of padding -- there's no explanation at all. I just point out it is a potential issue. So the reader has been warned, and if they have never heard of "compiler padding" they can go research that.

    Part of the wiki idea (which has made it successful) is that you can leave these opportunities for expansion available to others. That means
    1) you won't be discouraged from writing anything at all because you alone must complete and maintain it,
    2) other interested parties have something to get interested in and participate.

    However, most people will have priorities. I also did not explain the words "portability", "data", "memory", "file", "sequential", etc.

    Quote Originally Posted by phantomotap View Post
    You're a fool.
    After having spend most of the past few years learning programming, that's how I feel about a lot of self-appointed experts: they may be "authorities" in the sense of being good at what they do, but they could not explain their way out of a wet paper bag. They're great at starting flame wars relying on the fact that they can "hide some cards" (aka. a cherry-picker) but beyond inflating their own egos, it's meaningless. Eg, I have not seen you hand out much useful information to anyone, and I'm here a lot. You're a coot/crank (big deal). If you want to get off on ad hominem slinging of tish, etc, I don't mind doing that, altho IMO everything you need to know about "those scenarios" is crystal clear from the get go, and rarely changes in the process.

    I think that being at a "very advanced level of experience" leaves some people completely out of touch and unable to empathize with or understand the concerns of people new in the field. On the other hand, some of them are totally helpful, wise, etc, which kind of "puts the lie" to the aholes who are the exact opposite (many of them by intention, methinks).

    Also, there is the obvious point that different people think and learn in different ways. So this is the information "I wish I had when..." -- other people may feel completely differently. In which case, they should go look for another article written by someone else in a style they are more use to, etc. I do it all the time.

    You cannot be all things to all people, and people who pretend that they can usually know they are lying and have no intention of doing any good for anyone.
    Last edited by MK27; 02-25-2010 at 11:02 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #22
    Registered User
    Join Date
    Feb 2010
    Posts
    31
    Back on topic

    Here is the code i have now:

    Code:
    #include "stdafx.h"
    #include <iostream>
    #include <ctime>
    #include <string>
    #include <fstream>
    using namespace std;
     
    int main()
    {
     
        string cName;
        int cLeftOver;
        int cStr;
        int cIntel;
        int cAgi;
        int cCon;
        int cSpe;
          int cNin;
        int cPoints;
          
          
          cStr = 0;
          cIntel = 0;
          cAgi = 0;
          cCon = 0;
          cSpe = 0;
          cNin = 0;
     
        cPoints = 100;
        cout << "It's time to name your character! Please type your characters name: ";
        getline(cin, cName);
        cout << "Welcome to the game " << cName << "!" << endl << "You have 100 Character points to spend." << endl << "These points will be applied to your characters attributes. Lets begin!" << endl << endl;      
          cout << "---------------------------------" << endl;
          cout << "Strength:     " << cStr << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl;
          cout << "---------------------------------" << endl << endl;
     
          cout << "Strength is the attribute that applies to how much damage your mutant does." << endl << "How much strength would you like? (1-25)" << endl;
        cin >> cStr;
        if (cStr > 25)
        {   
            cout << "You're trying to set your Strength too high. Please choose between 1 and 25." << endl;
            cin >> cStr;
        }
          cPoints = cPoints - cStr;
          cout << endl << "You have " << cPoints << " points left!" << endl;      
          cout << "---------------------------------" << endl;
          cout << "Strength:     " << cStr << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl;
          cout << "---------------------------------" << endl << endl;
          
          cout << "Intelligence effects your ability to learn new skills and become stronger at those skills." << endl << "How much intelligence would you like? (1-25)" << endl;
          cin >> cIntel;
          if (cIntel > 25)
        {   
            cout << "You're trying to set your intelligence too high...which isnt very intelligent! Please choose between 1 and 25." << endl;
            cin >> cIntel;
        }  
          cPoints = cPoints - cIntel;
          cout << endl << "You have " << cPoints << " points left!" << endl;      
          cout << "---------------------------------" << endl;
          cout << "Strength:     " << cStr << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl;
          cout << "---------------------------------" << endl << endl;
     
          cout << "Agility affects how well your character can land attacks." << endl << "How much agility would you like? (1-25)" << endl;
          cin >> cAgi;
          if (cAgi > 25)
        {   
            cout << "You're trying to set your agility too high! Please choose between 1 and 25." << endl;
            cin >> cAgi;
        }   
          cPoints = cPoints - cAgi;
          cout << endl << "You have " << cPoints << " points left!" << endl;      
          cout << "---------------------------------" << endl;
          cout << "Strength:     " << cStr << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl;
          cout << "---------------------------------" << endl << endl;
          
          cout << "Constitution is what determines your HP and resistance to poisons" << endl << "How much constitution would you like? (1-25)" << endl;
          cin >> cCon;
          if (cCon > 25)
        {   
            cout << "You're trying to set your intelligence too high...which isnt very intelligent! Please choose between 1 and 25." << endl;
            cin >> cCon;
        }  
          cPoints = cPoints - cCon;
          cout << endl << "You have " << cPoints << " points left!" << endl;      
          cout << "---------------------------------" << endl;
          cout << "Strength:     " << cStr << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl << endl;
          cout << "---------------------------------" << endl << endl;
     
          cout << "Speed allows your character to land attacks sooner and more often" << endl << "How much speed would you like? (1-25)" << endl;
        cin >> cSpe;
        if (cSpe > 25)
        {   
            cout << "You're trying to set your speed too high. Please choose between 1 and 25." << endl;
            cin >> cSpe;
        }
          cPoints = cPoints - cSpe;
          cout << endl << "You have " << cPoints << " points left!" << endl;      
          cout << "---------------------------------" << endl;
          cout << "Strength:     " << cStr << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl;
          cout << "---------------------------------" << endl << endl;
     
          cout << "NinJutsu allows you to learn elite and secret techniques to attack your enemies with" << endl << "How much NinJutsu would you like? (1-25)" << endl;
        cin >> cNin;
        if (cNin > 25)
        {   
            cout << "You're trying to set your NinJutsu too high. Please choose between 1 and 25." << endl;
            cin >> cNin;
        }
          cPoints = cPoints - cNin;
          cout << endl << "You have " << cPoints << " points left!" << endl;      
          cout << "---------------------------------" << endl;
          cout << "Strength:     " << cStr << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl;
          cout << "---------------------------------" << endl << endl;
     
          if (cPoints > 0)
            {
                cout << "You did not spend all of your character points! You may still use " << cPoints << " points." << endl << "Which attribute would you like to add points to?" << endl;
                cout << "---------------------------------" << endl;
                cout << "1: Strength" << endl << "2: Intelligence" << endl << "3: Agility" << endl << "4: Constitution" << endl << "5: Speed" << endl << "6: Ninjutsu" << endl << "Please type the number corresponding with the attribute you want to change" << endl;
                cout << "---------------------------------" << endl;
                cin >> cLeftOver;
                
                if (cLeftOver = 1)
                {
                      cPoints = cPoints + cStr;
                      cout << "Strength is the attribute that applies to how much damage your mutant does." << endl << "How much strength would you like? (1-25)" << endl;
                      cin >> cStr;
                      if (cStr > 25)
                      {   
                      cout << "You're trying to set your Strength too high. Please choose between 1 and 25." << endl;
                      cin >> cStr;
                      }
                      cPoints = cPoints - cStr;
                      cout << endl << "You have " << cPoints << " points left!" << endl;      
                      cout << "---------------------------------" << endl;
                      cout << "Strength:     " << cStr << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl;
                      cout << "---------------------------------" << endl << endl;
                }
     
                if (cLeftOver = 2)
                {
                      cPoints = cPoints + cIntel;
                      cout << "Strength is the attribute that applies to how much damage your mutant does." << endl << "How much strength would you like? (1-25)" << endl;
                      cin >> cIntel;
                      if (cIntel > 25)
                      {   
                      cout << "You're trying to set your intelligence too high. Please choose between 1 and 25." << endl;
                      cin >> cIntel;
                      }
                      cPoints = cPoints - cIntel;
                      cout << endl << "You have " << cPoints << " points left!" << endl;      
                      cout << "---------------------------------" << endl;
                      cout << "Strength:     " << cIntel << endl << "Intelligence: " << cIntel << endl << "Agility:      " << cAgi << endl << "Constitution: " << cCon << endl << "Speed:        " << cSpe << endl << "NinJutsu:     " << cNin << endl;
                      cout << "---------------------------------" << endl << endl;
                }
    	}
    	ofstream fout((cName + ".txt").c_str());
    	fout << "cName = " << cName << ";" << endl << "cStr = " << cStr << ";" << endl << "cIntel = " << cIntel << ";" << endl << "cAgi = " << cAgi << ";" << endl << "cCon = " << cCon << ";" << endl << "cSpe = " << cSpe << ";" << endl << "cNin = " << cNin << ";" << endl;
        
    //   ifstream open((cName + ".txt").c_str());
    //   fin >> getline(2);
    
    	ifstream fin((cName + ".txt").c_str());
    	system ("PAUSE");
    	return 0;
    }
    And here is an example of a .txt file that is output currently by the program.
    Code:
    cName = Kamitsuna;
    cStr = 25;
    cIntel = 10;
    cAgi = 25;
    cCon = 20;
    cSpe = 10;
    cNin = 10;
    I tried to make the output in C++ format just in case it needed to be formatted later.

  8. #23
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,794
    Quote Originally Posted by MK27
    JSON is just a form of AJAX, isn't it?
    You must be aiming to produce the quote of the year with this hilarious question
    Hint: if JSON "is just a form of AJAX", then XML "is just a form of AJAX".

    Quote Originally Posted by kamitsuna
    I tried to make the output in C++ format just in case it needed to be formatted later.
    I do not understand your reasoning, and it sounds a little misguided. As phantomotap stated, the format that you have chosen allows for the entries to be placed in any order, but this actually makes life more difficult for you.

    It would be far easier if you had a format like this:
    Code:
    Kamitsuna;25 10 25 20 10 10
    So, you forbid the name from containing semi-colons, and now you can easily use std::getline() with ';' as the delimiter to read the name, then use operator>> to read the number statistics. Finally, you ignore the trailing whitespace including the newline sequence, and proceed to read the next line of statistics.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #24
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by laserlight View Post
    You must be aiming to produce the quote of the year with this hilarious question
    Hint: if JSON "is just a form of AJAX", then XML "is just a form of AJAX".
    What's so funny? It is what I thought/said it is (it developed out of AJAX, and it's prime purpose is handling AJAX style requests):
    Their own homepage: JSON
    Also:
    Quote Originally Posted by wikipedia on JSON
    Its main application is in Ajax web application programming, where it serves as an alternative to the XML format.
    And no, I didn't add that to the page So conceptually, AJAX includes JSON. I would not say XML is a form of AJAX -- I would say AJAX makes use of XML.

    Tch...anyway....

    Quote Originally Posted by kamitsuna View Post
    Back on topic
    You are too focussed on the details of your game, and you are not taking enough interest in programming. You are not trying to learn anything, you are too busy making things up. Let me explain:

    It goes against the whole grain of any good programming ethic to mindlessly string together a series of nearly identical events, when you could easily abstract an obvious pattern from them and write a single function to do all of it more easily.

    Your last post is just the same thing over and over and over again. It's tedious, and if you want to develop or change your method, you now have to do that over again 10 times too, etc.

    Have you written any functions yet? Time to start!
    Code:
    int setAttribute (int points, string name, string description) {
    	int value;
    	cout << endl << "You have " << points << " points left!" << endl;
    	cout << "---------------------------------" << endl;
    	cout << "Strength:     " << cStr << endl 
    		<< "Intelligence: " << cIntel << endl 
    		<< "Agility:      " << cAgi << endl 
    		<< "Constitution: " << cCon << endl 
    		<< "Speed:        " << cSpe << endl 
    		<< "NinJutsu:     " << cNin << endl;
    	cout << "---------------------------------" << endl << endl;
    	cout << description << endl 
    		<< "How much " << name << " would you like? (1-25)" << endl;
    	cin >> value;
    	while (value > 25 || value < 1)
    	{
    		cout << "That's not valid! Please choose between 1 and 25." << endl;
    		cin >> value;
    	}
    	return value;
    }
    Presuming cStr, cIntel, cAgi, cCon, cSpe, cNin, and cPoints are global, you can know call this function like this:
    Code:
    cStr = setAttribute(cPoints, "strength",
    	"Strength is the attribute that applies to how much damage your mutant does.");
    cAgi = setAttributes(cPoints, "agility",
            "Agility affects how well your character can land attacks.");
    You may instead want to put all these in a struct and pass that around.

    The point is, you need to think of ways to actually apply programming concepts (like functions and compound datatypes) to what you are doing, or it is just a waste of time. Almost certainly, at this point you just need to keep doing simple exercises -- it is unlikely that anything you write right now will be useful for anything. So the less time you spend on extraneous and irrelevant details, and the more time you spend learning to use as much C++ syntax as you can, the sooner you will be able to sit down and start writing a game that which actually end up as a working program.

    I hope I don't seem mean, I am just trying to get you to focus and think about what you are doing.
    Last edited by MK27; 02-26-2010 at 05:52 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  10. #25
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,794
    Quote Originally Posted by MK27
    What's so funny? It is what I thought/said it is (it developed out of AJAX, and it's prime purpose is handling AJAX style requests):
    Their own homepage: JSON
    Look at what that page claims JSON is: "JSON (JavaScript Object Notation) is a lightweight data-interchange format." How can a data-interchange format be "a form of AJAX", when AJAX is more than a data-interchange format?

    Quote Originally Posted by MK27
    So conceptually, AJAX includes JSON. I would not say XML is a form of AJAX -- I would say AJAX makes use of XML.
    You might say that AJAX includes JSON, but it does so in the sense that it makes use of JSON, should you choose to use it to implement AJAX techniques. Recall that AJAX stands for "Asynchronous Javascript And XML". So, if you want to posit that making use of JSON to implement AJAX techniques means that AJAX includes JSON and that JSON is thus a form of AJAX, it follows as strongly that AJAX includes XML and XML is a form of AJAX.
    Last edited by laserlight; 02-26-2010 at 06:06 AM.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #26
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Mmm. Well, I was not initially aware that JSON included it's own message format, which is why I raised the question -- I thot it was just an AJAX function library (which is still what it appears to be).

    The difference between that and XML would be: you have such a thing as an AJAX/JSON routine which makes use of an XMLHttpRequest object. The object uses XML for formatting. The routine is written in javascript. AJAX is a programming technique/exploit. (And in fact the XML aspect is largely opaque).

    So AJAX and JSON are javascript (JSON may be some other things as well). XML is not javascript, it does not involve any "Turing complete" language -- it is just a mark-up protocol. Hence, it makes sense to call JSON "a form of AJAX" but it does not make sense to say that of XML.
    Last edited by MK27; 02-26-2010 at 06:23 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #27
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,282
    it's prime purpose is handling AJAX style requests
    *shrug*

    I see it used most often in serializing objects for database storage.

    From a C/C++ perspective, programming for that is not a beginner activity.
    There are more than a few libraries dedicated to serializing native (int, double, etc.) and STL (std::vector<???>, etc.) instances into various forms of XML, JSON, and similar that is as simple as providing a variable association table, in plaintext, and calling a simple API.

    Back on topic
    Wish Granted. (I feel bad for hijacking the thread. I almost lost the last post from the OP.)

    Soma

    Code:
    #include <cctype>   // std::isspace std::isalpha std::isdigit
    #include <fstream>  // std::ifstream
    #include <iostream> // std::cout std::cerr
    #include <sstream>  // std::istringstream
    #include <string>   // std::string
    
    // a "dumb" parser (technically this is only a simple exclusive lexer or
    // tokenizer relying on additional semantic information from higher level
    // routines for actual parsing) based on `std::string' iterators
    // ignores extra whitespace characters ('\n' '\t' '\v' '\b' '\r' '\f' ' ')
    // between parsing tokens
    namespace parser
    {
    	// we use this `typedef' exclusively
    	typedef std::string::iterator citerator;
    
    	// this structure stores the results of every
    	// funtion in our parser library
    	struct result_type
    	{
    		bool success;     // whether of not the individual parse is successful (if success is true the other members are valid)
    		citerator cursor; // an iterator reference to the first character to process
    		citerator end;    // an iterator reference to the next element after the last element to process
    	};
    
    	// this function, used by `variable_name' below, determines
    	// the set of characters valid for a variable name which
    	// consists of uppercase letters (A-Z), lowercase
    	// letters (a-z), numbers (0-9), and the underscore (_)
    	bool isvvnchar
    	(
    		char character
    	)
    	{
    		return(std::isalnum(character) || '_' == character);
    	}
    
    	// parses a variable name where a variable name
    	// starts with a letter character and terminates
    	// with an invalid character as determined by the above
    	// `isvvnchar' function
    	result_type variable_name
    	(
    		citerator cursor,
    		const citerator end // we don't want to change this by accident
    	)
    	{
    		// setup the return value in case of failure
    		result_type result = {false,  cursor, end};
    		// trim beginning whitespace characters
    		while(std::isspace(*cursor) && end != cursor)
    		{
    			++cursor;
    		}
    		// the first character must be a character
    		if(std::isalpha(*cursor))
    		{
    			// update the result iterator in case of success
    			result.cursor = cursor;
    			while(isvvnchar(*cursor)  && end != cursor)
    			{
    				++cursor;
    			}
    			// so far we have a valid name
    			// it is not the job of this function to determine
    			// if the result is meaningful if it could be a
    			// name it is a name and we have succeeded
    			// `cursor' currently references the next character
    			// after the last character match (from `isvvnchar')
    			// or `end' which matches our definition of a good
    			// result as above
    			result.end = cursor;
    			// finally we need to flag the result as successful
    			result.success = true;
    		}
    		return(result);
    	}
    
    	// parses integer values (kinda duh)
    	result_type integer_value
    	(
    		citerator cursor,
    		const citerator end
    	)
    	{
    		result_type result = {false,  cursor, end};
    		while(std::isspace(*cursor) && end != cursor)
    		{
    			++cursor;
    		}
    		if(std::isdigit(*cursor))
    		{
    			result.cursor = cursor;
    			while(isdigit(*cursor)  && end != cursor)
    			{
    				++cursor;
    			}
    			result.end = cursor;
    			result.success = true;
    		}
    		return(result);
    	}
    
    	// this function, used by `name_value' below, determines
    	// the set of characters valid for a name value which
    	// consists of uppercase letters (A-Z), lowercase
    	// letters (a-z), the space ( ) character
    	bool isvsvchar
    	(
    		char character
    	)
    	{
    		return(std::isalpha(character) || ' ' == character);
    	}
    
    	// trims beginning spaces so the name must start with a
    	// letter
    	result_type name_value
    	(
    		citerator cursor,
    		const citerator end
    	)
    	{
    		result_type result = {false,  cursor, end};
    		while(std::isspace(*cursor) && end != cursor)
    		{
    			++cursor;
    		}
    		if(isvsvchar(*cursor))
    		{
    			result.cursor = cursor;
    			while(isvsvchar(*cursor)  && end != cursor)
    			{
    				++cursor;
    			}
    			result.end = cursor;
    			result.success = true;
    		}
    		return(result);
    	}
    
    	// this function parses the assignment portion of the line
    	result_type assignment
    	(
    		citerator cursor,
    		const citerator end
    	)
    	{
    		result_type result = {false,  cursor, end};
    		while(std::isspace(*cursor) && end != cursor)
    		{
    			++cursor;
    		}
    		if('=' == *cursor)
    		{
    			result.cursor = cursor;
    			++cursor;
    			result.end = cursor;
    			result.success = true;
    			// if at this point you've noticed a strong
    			// resemblance between the four parsing function
    			// you should congratulate yourself
    			// there exists a straightforward way
    			// of merging the shared source of these
    			// functions for this sort of parser
    			// allowing you to build more "elemental
    			// parsers from simple functions
    			// that define the range and domain
    			// of the function in question
    		}
    		return(result);
    	}
    }
    
    struct character_sheet
    {
    	std::string cName;
    	int cLeftOver;
    	int cStr;
    	int cIntel;
    	int cAgi;
    	int cCon;
    	int cSpe;
    	int cNin;
    	int cPoints;
    };
    
    // for now only allows one character per file
    // more work needed to allow more than one character
    // per file
    // overwrites the old character if additional statements are found
    void parse_character
    (
    	std::ifstream & fin,
    	character_sheet & entity
    )
    {
    	using namespace std;
    	int linenum(0);
    	string line;
    	// get a line from the file
    	while(getline(fin, line))
    	{
    		int statementnum(0);
    		string statement;
    		istringstream sin(line);
    		++linenum;
    		// build a statement line using our delimiter (;)
    		// and loop until there are no more statements
    		while(getline(sin, statement, ';'))
    		{
    			using namespace parser;
    			result_type result;
    			++statementnum;
    			result = variable_name(statement.begin(), statement.end());
    			if(true == result.success)
    			{
    				// construct a `string' variable from the parsed information
    				// that the constructor for a `string' accepts these
    				// parameters is no accident (it is what we wanted)
    				string variable(result.cursor, result.end);
    				// compare the variable with what we understand (semantic)
    				if("cName" == variable)
    				{
    					// remember from above
    					// the `end' member of `result_type'
    					// references one element beyond the last
    					// element parsed by the function
    					// that generated the instance
    					// in other words, we use the "old" result
    					// to continue parsing
    					// we have a variable name
    					// we need to see if we have a valid
    					// assignment statement so we obviously
    					// try to parse that next
    					result = assignment(result.end, statement.end());
    					if(true == result.success)
    					{
    						// we have an assignment statement
    						// now we need to parse the value being assigned
    						// for the "name" variable the value
    						// is expected to be a name value as
    						// determined by the parsers
    						result = name_value(result.end, statement.end());
    						if(true == result.success)
    						{
    							// we have successfully parsed a name value assignment statement
    							// now we assign that value to the entity
    							// this constructs a temporary string
    							// from the parsed data and assigns the result
    							// to the entity
    							entity.cName = string(result.cursor, result.end);
    						}
    						else
    						{
    							cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    						}
    					}
    					else
    					{
    						cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    					}
    				}
    				// checking for more variables assignments we understand
    				else if("cStr" == variable)
    				{
    					result = assignment(result.end, statement.end());
    					if(true == result.success)
    					{
    						// we have an assignment statement
    						// now we need to parse the value being assigned
    						// for the "cStr" variable (and the others) the value
    						// is expected to be a integer value as
    						// determined by the parsers
    						result = integer_value(result.end, statement.end());
    						if(true == result.success)
    						{
    							// we have successfully parsed an integer value statement
    							// now we assign that value to the entity
    							// this constructs a temporary `istringstring'
    							// from the parsed data and attempts to
    							// "read" the result and assign the result
    							// to the associated value of the entity
    							istringstream vin(string(result.cursor, result.end));
    							int tempvalue(0);
    							if(vin >> tempvalue)
    							{
    								entity.cStr = tempvalue;
    							}
    							else
    							{
    								cerr << "not an integer value? (" << linenum << ',' << statementnum << ")\n";
    							}
    						}
    						else
    						{
    							cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    						}
    					}
    					else
    					{
    						cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    					}
    				}
    				else if("cIntel" == variable)
    				{
    					result = assignment(result.end, statement.end());
    					if(true == result.success)
    					{
    						result = integer_value(result.end, statement.end());
    						if(true == result.success)
    						{
    							istringstream vin(string(result.cursor, result.end));
    							int tempvalue(0);
    							if(vin >> tempvalue)
    							{
    								entity.cIntel = tempvalue;
    							}
    							else
    							{
    								cerr << "not an integer value? (" << linenum << ',' << statementnum << ")\n";
    							}
    						}
    						else
    						{
    							cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    						}
    					}
    					else
    					{
    						cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    					}
    				}
    				else if("cAgi" == variable)
    				{
    					result = assignment(result.end, statement.end());
    					if(true == result.success)
    					{
    						result = integer_value(result.end, statement.end());
    						if(true == result.success)
    						{
    							istringstream vin(string(result.cursor, result.end));
    							int tempvalue(0);
    							if(vin >> tempvalue)
    							{
    								entity.cAgi = tempvalue;
    							}
    							else
    							{
    								cerr << "not an integer value? (" << linenum << ',' << statementnum << ")\n";
    							}
    						}
    						else
    						{
    							cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    						}
    					}
    					else
    					{
    						cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    					}
    				}
    				else if("cCon" == variable)
    				{
    					result = assignment(result.end, statement.end());
    					if(true == result.success)
    					{
    						result = integer_value(result.end, statement.end());
    						if(true == result.success)
    						{
    							istringstream vin(string(result.cursor, result.end));
    							int tempvalue(0);
    							if(vin >> tempvalue)
    							{
    								entity.cCon = tempvalue;
    							}
    							else
    							{
    								cerr << "not an integer value? (" << linenum << ',' << statementnum << ")\n";
    							}
    						}
    						else
    						{
    							cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    						}
    					}
    					else
    					{
    						cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    					}
    				}
    				else if("cSpe" == variable)
    				{
    					result = assignment(result.end, statement.end());
    					if(true == result.success)
    					{
    						result = integer_value(result.end, statement.end());
    						if(true == result.success)
    						{
    							istringstream vin(string(result.cursor, result.end));
    							int tempvalue(0);
    							if(vin >> tempvalue)
    							{
    								entity.cSpe = tempvalue;
    							}
    							else
    							{
    								cerr << "not an integer value? (" << linenum << ',' << statementnum << ")\n";
    							}
    						}
    						else
    						{
    							cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    						}
    					}
    					else
    					{
    						cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    					}
    				}
    				// if at this point you've not seen the obvious
    				// repetition you should be ashamed of yourself
    				// there is a straightforward way
    				// to pull out this repetition into a function
    				// which can simply be called once per statement
    				else if("cNin" == variable)
    				{
    					result = assignment(result.end, statement.end());
    					if(true == result.success)
    					{
    						result = integer_value(result.end, statement.end());
    						if(true == result.success)
    						{
    							istringstream vin(string(result.cursor, result.end));
    							int tempvalue(0);
    							if(vin >> tempvalue)
    							{
    								entity.cNin = tempvalue;
    							}
    							else
    							{
    								cerr << "not an integer value? (" << linenum << ',' << statementnum << ")\n";
    							}
    						}
    						else
    						{
    							cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    						}
    					}
    					else
    					{
    						cerr << "bad assignment? (" << linenum << ',' << statementnum << ")\n";
    					}
    				}
    			}
    			else
    			{
    				cerr << "bad variable? (" << linenum << ',' << statementnum << ")\n";
    			}
    		}
    	}
    }
    
    int main()
    {
    	using namespace std;
    	character_sheet player = {"", 0, 0, 0, 0, 0, 0, 0, 0};
    	ifstream fin("player.txt");
    	parse_character(fin, player);
    	cout << player.cName << '\n';
    	cout << player.cStr << '\n';
    	cout << player.cIntel << '\n';
    	cout << player.cAgi << '\n';
    	cout << player.cCon << '\n';
    	cout << player.cSpe << '\n';
    	cout << player.cNin << '\n';
    	return(0);
    }

  13. #28
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Sheesh, we are going to scare this poor kid off.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  14. #29
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,282
    So AJAX and JSON are javascript [...] make sense to say that of XML.
    JSON is not Javascript. JSON is a declarative subset of the Javascript grammar allowing only literal expressions.

    With your logic a semicolon delimited value table is C++.

    Sheesh, we are going to scare this poor kid off.
    That was, honestly, my intent. He should start smaller with something easy to parse. A strict format like what LL proposed would be perfect.

    Soma

  15. #30
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by phantomotap View Post
    JSON is not Javascript. JSON is a declarative subset of the Javascript grammar allowing only literal expressions.
    With your logic a semicolon delimited value table is C++.
    Yeah, you're right -- on closer inspection it does not appear to include any library functions at all. My impression was that it provided some "prototype" style functionality client side:
    Prototype JavaScript framework: Easy Ajax and DOM manipulation for dynamic web applications
    But maybe not. This makes the name "JavaScriptObjectNotation" misleading to ridiculous, since it has nothing to do with js objects and classes.

    Sheesh, we are going to scare this poor kid off.
    That was, honestly, my intent. He should start smaller with something easy to parse. A strict format like what LL proposed would be perfect.
    Soma
    Well, hopefully s/he will see the phantomotap code and be inspired to aim high.
    @kamitsuna: hopefully you see the point here. Your priority should be to learn programming, not make a game, because until you learn some programming, making a game is just fantasy.
    Last edited by MK27; 02-26-2010 at 07:00 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Page 2 of 4 FirstFirst 1234 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  3. Bitmasking Problem
    By mike_g in forum C++ Programming
    Replies: 13
    Last Post: 11-07-2007, 11:24 PM
  4. File Database & Data Structure :: C++
    By kuphryn in forum C++ Programming
    Replies: 0
    Last Post: 02-24-2002, 10:47 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21