C/C++ :: Create Class Instances From Text File Stream

Nov 10, 2014

I am trying to do some exercises but am struggling at the moment. The first task was to create a class (Planet), then allow the user to edit their entry or view it.

The second one is to create class instances from a text file. The file contains a new planet on each line in the form: 'id x y z' where x/y/z are its coordinates. As the file can have more then one lines, it has to dynamically create an undefined amount of class instances.

To do this I used 'new' and it works ok - it prints each one out to the screen as you go so you can see it working. However... I'm trying to get into good habits here and am encapsulating the class which is where I am getting stuck. I can read from the class but cannot put the values from the file into the class.. ..using the member functions I have created anyway.

My code so far is:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Planet {
private:
int id=0;
float x_coord=0.0, y_coord=0.0, z_coord=0.0;
public:
int GetID(){return id;}

[code]....

If I change the SetID etc to just p->id, p->x_coord etc it works fine. But I'd rather find a way to do it that keeps the encapsulation. Using p->z_coord etc requires that you change the class variables from private to public.

The question I have been given is this:

Define and implement a function, generate planet, that takes a stream argument that has already been connected to a file (i.e. the argument is istream& fin). The function must create a new instance of planet using new and read its details from the next line in the file.Each line of the file is in the format id x y z.The function must return the newly created planet.

Also, how would you go about 'viewing' one specific class instance once they've been created? So say the file had 5 lines, line three was '4 6 2 6'. How would I go about viewing that planet afterwards? I don't think thats required but... I'm just wondering Although I'm also wondering, are we actually creating a new class instance for each line here? Or just destroying the previous one?

View 14 Replies


ADVERTISEMENT

C++ :: Class Instances To Text File

Mar 29, 2015

Code:
#include<iostream>
#include<conio.h>
#include<string.h>
#include<ostream>
#include<fstream>
#include<iomanip>
using namespace std;
class MathProblem {

[Code] ...

So my program is quite simple, have the user answer the answer to a question, and then compare with the correct answer. I needed to implement an inheritance of MathProblem in my second class aswell.

The program runs as I intend but I wish to have the data forwarded to a text file. After that I must read back to the command prompt the text file contents. It's fairly easy for simple statements but I don't understand how to forward all my data from my classes.

View 3 Replies View Related

Visual C++ :: File Stream Change Its Address During Writing Text Contents To The Stream

Apr 29, 2013

I wrote a program to write text contents to file stream through fputs, the file stream address was changed in the middle of writing text content to the stream (11% text content have been put into the file stream), that cause the file stream pointer can be evaluated problem and raise exception on stream validation code in fputs library function, my question is what things could go wrong to make file stream pointer changed its address to something else or a NULL pointer if the file stream have not been flushed and closed.

View 5 Replies View Related

C++ :: Read In Lines From A File / Store In Variables Then Construct Instances Of Class

Aug 22, 2013

I can't get my code to compile, i need to read in lines from a file and store them in variables. Then i have to construct instances of my class for how many lines there are in the file and take those variables into them.

I'm getting this error :

"a2.cpp:40: error: cannot convert `Employee' to `Employee*' in assignment"

#include<iostream>
#include<string>
#include<fstream>
void displayInfo();
using namespace std;
class Employee{

[Code] .....

View 1 Replies View Related

C++ :: String Stream Object And Text File Data Access

Jan 21, 2014

I have two puzzling issues I am dealing with.

Issue 1: I am using a stringstream object in a block of my program that needs to be visited repeatedly depending on a user's selection from a menu. I want the contents of this stringstream object to be cleared any time control gets to this part of the program. I have tried the clear and flush functions to no avail.

Issue 2: I am reading data from a source text file that would be regularly changed during the course of program run. After the program run is over, I am supposed to save the results(which is basically the source text file AND all updates) in a destination file. This destination file would then serve as the source file when next the program is run. In other words, I want a scenario where my results overwrite the original contents of the source file; implying that my source and destination files are now one, pretty much. How can I do this?

View 7 Replies View Related

C/C++ :: Create Local Instances Of A Global Variable?

Oct 4, 2012

is it possible to have a global variable pointing to a different address depending on the thread?

Imagine one would like to use threads with the loop:

for (i=0;i<n;i++){
globalPointerVariable=getAddress(i);
DoThingsUsingThe_globalPointerVariable();
}

View 4 Replies View Related

C++ :: Dynamic Memory - Create Multiple Instances Without Explicitly Call Delete

Mar 28, 2014

look at this code:

#include <iostream>
using namespace std;
class teste

[Code]....

Each time i call "x = new teste();" the previous object is deleted? Does this code cause any sort of memory leak?

View 1 Replies View Related

C++ ::  how To Correctly Initialize Instances Of A Class

Feb 1, 2015

I am struggling to understand what the correct way to initialize instances of a class for object orient programming is.

If I am not mistaken, there are 2 methods to initialize an instance "instance_name" of CLASS1 by calling the constructor:

(1) CLASS1 instance_name(argument);
(2) CLASS1 instance_name=CLASS1(argument);

As it turns out, I cannot use method (1) when I try to initialize a private instance inside another class. But I can use it in the main() code. I hope the code below will explain what I mean. Why only method (2) will work inside another class? Or is there another fundamental mistake I am making?

(BTW: I used CodeBlocks 13.12 with GNU GCC compiler for this example)

#include <iostream>
using namespace std;
class CLASS1{

[Code].....

View 6 Replies View Related

C++ :: Static Const Class Instances?

Jun 17, 2012

i have this rather large class, which (in a way) somehow resembles a custom dialog control). This control is supposed to display data, which it does just fine. To do so, it maintains a

byte settings[10];

array, which holds information on how to display the data.

There are multiple ways to represent this custom set of data.In order to remain flexible in representing it, i thought of implementing some sort of DisplayProvider, which can be registered to the base class and provides that settings byte array.

Preferably, i would now have a set of static const instances of this provider.Using a struct would work nicely here:

PHP Code:

struct DisplayProvider
{
int settings[10];
}
static const DisplayProvider prov1 = {1,2,3,4,5,6,7,8,9,0}; 

The problem: The DisplayProvider would have to do some pre-processing, before handing over control to the base class, which then does the main work.I would end up with something like this:

PHP Code:

class DispalyProvider
{
baseclass* owner;
 int settings[10];
void PreProcessing(...);//ends up calling the owner.Processing(...) function
}; 

The main thing here is, that i dont really see a way to create a stock of default "static const DisplayProvder = {...}"s, as i could when using a struct.

View 7 Replies View Related

C++ :: Hold Vector Of Pointers In Same Class As Instances Of Those Objects?

Feb 10, 2015

Using SFML, I had a Board class which held multiple vectors of all of my object types in the game, and then it also held a vector of pointers to the memory addresses of these object instances, like this

class Board{
//...
std::vector<AbstractObject*> GetAllLevelObjects(){ return allLevelObjects; }
//so these are used to hold my object instances for each level

[Code]....

When looping through this vector and drawing the sprites of the objects, I get the runtime error 0xC0000005: Access violation reading location 0x00277000. I solved this error by storing the vector of pointers in the class that holds my Board instance, but I'm wondering why only this solution worked? Why couldn't I just have my vector of pointers in the same class that the instances of those objects were in?

View 2 Replies View Related

C :: Create File To Write Text And Read Back The File Content

Mar 15, 2013

The Objective Of This Program Is To Create A File To Write Text And Read Back The File Content. To Do That I Have Made Two Function writeFile() To Write And readFile() To Read.The readFile() function works just fine but writeFile() doesn't.

How writeFile() function Works? when writeFile() function Execute It Takes Characters User Type And When Hit Enter(ASC|| 10) It Ask "More?(Y/N)" That Means What User Want? Want To Go Next Line Or End Input?

If "Y" Than Inputs Are Taken From Next Line Else Input Ends.

But The Problem Is When Program Encounters ch==10 It Shows "More?(Y/N)" And Takes Input In cmd variable.If cmd=='Y' I Mean More From Next Line Than It Should Execute Scanf Again To Take ch I Mean User Input.But Its Not!!! Its Always Showing "More?(Y/N)" Again And Again Like A Loop.

Code:
#include <stdio.h>
void writeFile(void);
void readFile(void);
int main(){

[Code].....

View 5 Replies View Related

C :: Create A File And Save Text In It In PDF Format

Feb 13, 2014

My objective is to create a file and save some text in it. But the twist is that file should be created in pdf format.

I have written following code:

Code:
#include<stdio.h>

Code:
int main() { FILE *fp;
char ch;
fp=fopen("file.pdf","w");
fprintf(fp, "%PDF-1.3"); //to initiate data storage in pdf file
printf(" Enter data to be stored in to the file:");
while((ch=getchar())!=EOF)
putc(ch,fp);
fclose(fp);
return 0;}

Now my file is created in pdf format, but when I open it by double click on it, it is not open and gives the message like: "Error in opening document. This file is damaged and could not be repaired."

View 1 Replies View Related

C/C++ :: Create And Write To Text File And Then Read From It?

Mar 26, 2014

I have looked through te tutorials here, and even google it, as well as tried to follow the power points from my class..but I still can't seem to figure out how to make this code work correctly.. Basically I have to create a file called grade and write to it a student name and their grade score, and then read from the file all students names and there grade and display this on the screen as well as calculate the grade average for all of the students and display it.

Well I am able to write to the text file, but I can't seem to get the rest to work. I can't figure out how to read from the text file..Here is my code below.

write a sample code that does something similar write to text file string and numbers and then reads from it.

#include <iostream>
#include <fstream>
using namespace std;

[Code].....

View 6 Replies View Related

C++ :: Create Random Matrix And Print It Out In Text File

Feb 11, 2014

I am trying to create a random 3x3 matrix and print it out in a text file using basic functions. My code below will not compile.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//nxn Matrix = 3x3
const int ROWS = 3;
const int COLS = 3;

[Code] .....

View 2 Replies View Related

C++ :: Search Specified File For All Instances Of Substring

Mar 24, 2012

I'm trying to search a specified file for all instances of substring "abbaa."

The professor is making us use a 6x3 array in order to understand finite state machines.

Well the code I wrote runs perfectly, but the case for '/n' doesn't catch. It just flows through without it.

Significant portion of code:

Code:
if(fin) {
fin >> inChar;
while(fin) {
switch(inChar) {
case 'a':
currentState = state[currentState][a];

[Code] .....

View 3 Replies View Related

C++ :: Create User Defined Class And Have Access In Separate Header File From Main

Mar 15, 2013

I am a beginner with C++, taking a class right now. The lab this week is to create a user defined class and have it accesses in a separate .h header file from the main.

I think I'm finding my way through it, but I'm getting a complie error that makes no sense to me:

1> Resistor.cpp
1>c:users omdocumentsschoolcomp 220week 2lablab 2.2lab 2.2
esistor.h(11): error C2146: syntax error : missing ';' before identifier 'resistor'
1>c:users omdocumentsschoolcomp 220week 2lablab 2.2lab 2.2

[Code] .....

Here is the first portion of the .h file:

#include <iostream>
#include <iomanip>
#include <Windows.h>
#include <math.h>
#include <string>

class CResistor{
double res1, res2, res3, percentage, Nominal, Tolerance;

[Code] ....

View 16 Replies View Related

C++ :: Read Info From Text File Into Class?

May 22, 2014

I'm having trouble in getting my program to read from a file and put all the proper data into its proper class variables. I have a class (called Champion) that has string variable for a name and a vector of strings for items. I also have a vector of Champion that holds multiple champions. Here's my code:

Champion.hpp
#ifndef CHAMPION_HPP_INCLUDED
#define CHAMPION_HPP_INCLUDED
#include <iostream>

[Code].....

View 3 Replies View Related

C/C++ :: How To Structure And Write A Class For Text File Streams

Apr 20, 2014

I need to make a program which reads multiple lines from a text file and stores that information in a vector of structs(the vector class template also needs to be custom made).

One of my requirements is to have a class dedicated for I/O for the text file. At the moment I can't seem to get a way to input the data from a file into a vector from an InputOutput class. This is my code:

InputOutput.h

#include <ostream>
#include <fstream>
#include "Share.h"
#include <string>
#include "Vector.h"
class InputOutput {

[Code] ....

This is the menu selection function in the menu.cpp where i figured i would call the Input file and store it from case 1. I think I'm doing it wrong though. Is there a better way of doing this because at the moment i am getting some errors such as error LNK2019.

void Menu::UserMenuSelection() {
Vector<Share> shares;
std::ifstream infile;
switch (menuOption) {

[Code] ....

View 2 Replies View Related

C/C++ :: How To Write Class Objects To Text File Using Fstream

Jan 15, 2014

I need to a simple example for writing class' objects to a text file using fstream , I tried to search the forums and I found binary examples but not for to a text file.

View 8 Replies View Related

C# :: Method Of Mapping Text File Dictionary To Class Fields

Jan 21, 2014

So I'm rewriting an old project of mine, and I'm trying to determine if there's truly any better way to map the data taken from a text file "dictionary" into the correct class fields for further processing. For example:

FNAME=MY_FIRST_NAME
ADDR=123 SOMEWHERE LN, NOWHERESVILLE, TX 01234
LNAME=MY_LAST_NAME
TOTCALLS=47

In each of these, I'd need the "value" (MY_FIRST_NAME, MY_LAST_NAME, etc) from the "keys" (FNAME, LNAME, etc) to be mapped to the proper class fields. Say, for example, I had this:

Class DataProcessing {
public string Address;
public string FirstName;
public string LastName;
public int TotalCalls;
...
}

I would need DataProcessing.Address to be set to the value in the ADDR key/value pair. The same would be true for each other field. The problem is that based on the text file's source (which isn't under my control, and won't be changed anytime soon), the key/value pairs are not always in the same place...so a second file could have the data as such:

TOTCALLS=47
ADDR=123 SOMEWHERE LN, NOWHERESVILLE, TX 01234
LNAME=DARKPOETCC'S LAST NAME
FNAME=DARKPOETCC'S FIRST NAME

Any smarter way to do this than looping through each line that was read in from the file, and determining where it belongs, such as (pseudo code follows):

IF FieldName == "TOTCALLS" THEN
//Assign to TotalCalls field
ELSEIF FieldName == "ADDR" THEN
//Assign to Address field
ELSEIF FieldName == (You get the picture...)
//Do thing N_Field

View 9 Replies View Related

C++ :: File Stream Loop

Dec 4, 2013

Why does my loop loops 3 times when i have only 2 line of data in my file? From the cout << s.size , when i run it will show 1,2,3.

Information in txt file
Code:
local john 10/2/1990
international tom 2/5/2000 output Code: local john 10/2/1990
international tom 2/5/2000
international tom 2/5/2000 Code: ifstream in(filename);

[Code] ....

View 4 Replies View Related

C++ :: Copying One File To Another - I/O Stream

Mar 4, 2013

I'm having some trouble with copying one I/O stream into another. I've put the first one into an array but I cannot get my second prompt to copy the .txt file the first prompt sees and outputs to the console. When I try and grab the info from the .txt file my first prompt sees I only see blank space in my .txt file.

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <fstream>
using std::ifstream;
using std::ofstream;

[Code] .....

View 1 Replies View Related

C++ ::  reading Stream Value From A File?

Oct 13, 2013

#include<fstream.h>
#include<conio.h>
#include<string>
class CLS {
public : string name;

[code]....

I have used the above code to write the class instanc to a file "Text.txt"...But it seems that "f.write((char*)&c, sizeof(CLS));" is not working properly with string. The data can easily be written using stream object!

#include<fstream.h>
#include<conio.h>
#include<string>
class CLS {
public : string name;

[code]....

When I tried to read the data on the file...., it gave an error "Thread stopped...violation.."

View 7 Replies View Related

C++ :: File Stream And String Extraction?

Apr 7, 2014

I am currently trying to read in a file that takes in the input in the following form.

Code:
HANK>25 BOB>31 AL>54
BILL>41 ABE>63 JEFF>50

I have tried the following solution:

Code:
#include<ifstream>
#include<iostream>
using namespace std;
struct node
{
string name;
int age;
);
int main ()
{

[code]....

The problem is a.name, it's extracting the entire string before the space character causing p.age to contain "BOB" and so on. I've tried using p.get(p.name, sizeof(p.name), '-') with '-' as the delimiter and p.getline() using a character array instead of a string. How would it be possible to only copy the string into a.name before the '>' character?

View 1 Replies View Related

C++ :: Redirecting A File Stream To Stdout

Sep 20, 2013

Let us assume I have a program that takes the name of the output file from the command line. Now let us assume that a decided not to give any output file location but wanted my program to to print my strings/ints ... directly to stdout. how would one do this using file streams? Using file pointers and c that is pretty straight forward but how would i achieve this in c++.

View 12 Replies View Related

C++ :: File Input Stream Not Loading?

May 9, 2014

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

[Code]....

I'm trying to load a file input stream to load all the character content into a variable (say from a .java file for example), but for some reason whenever I type in the name of the file I want to stream I get the report: RUN FAILED (exit value 1, total time 2s)

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved