Difficulty with C++

Status
Not open for further replies.
I'm pretty sure that arrays do automatically pass by reference, because otherwise there is no way that the program would be working properly.

Don't think for an instant that I am snubbing your advice, or that I am failing to see its value. It's just that my knowledge of structs is lacking, and my knowledge of pointers even more so. I can try to reorganize my program that way, but I'll probably fail miserably; looking up these things online doesn't tend to help me comprehend material nearly as well as attending lectures and labs.

Anyway, I'm trying a radically new type of movement AI, at the recommendation of someone who has already taken this class (and its follow-up class, to boot). Basically, I'm trying to make it so that when given the choice, the AI will always move right relative to the direction it is facing. It kind of works, but it exhibits some odd behaviors sometimes. If I incur further problems, I will post the code.

Also, how the heck do you define the dimensions of an array? Whenever I declare an "int x" and say that the array is "maze[x][x]", it tells me "error: expression must have a constant value".
 
Last edited:
It's just that my knowledge of structs is lacking, and my knowledge of pointers even more so.

Just take your usual variables, where you declare them, i.e., int maze[20][20];, and put them inside a 'box', like:

typedef struct
{
int i, j;
int maze[20][20];
} maze_t;

maze_t maze;

Then you can just reference maze.maze[maze.i][maze.j] and if you want to pass the array and i,j around into functions, you can do this:

void MyFunc (maze_t *pMaze)
{
pMaze->maze[pMaze->i][pMaze->j] = something;
}

MyFunc(&maze);

Also, how the heck do you define the dimensions of an array? Whenever I declare an "int x" and say that the array is "maze[x][x]", it tells me "error: expression must have a constant value".

You have to use dynamic allocation, like so:

int x = 5;
int *maze = new int[x][x];

And don't forget when done....
delete maze;

I'll let Blitzzo verify my C++ syntax... personally, I'd do:

int **maze = (int**)malloc(sizeof(int)*x*x);
free(maze);
 
Suppose I'll mention that this topic inspired me to create something along these lines while half asleep (insomnia) last Sunday night out of boredom:

http://cstrfan.info/files/misc/other/mazetraverse.zip

Code:
/* Read a maze from a text file and (attempt) to solve it.
 * Matthew Walsh (Inuyasha) 10.18.2010
 * Made in a couple hours of boredom.
 ***************************************/

#include <iostream>
#include <fstream>

#define WALL    '#'
#define PATH    'x'
#define BLOCKED '@'

using namespace std;

// Memory for maze is allocated dynamically to allow for the maze size
// to only be limited by the amount of memory that can be allocated
char *maze;
int width  = 0;
int height = 0;
int stepnum = 0;

// Open input and create our maze.
void initalize(void)
{
	ifstream input;
	bool midline = false;
	char newchar;
	char *mptr;
	int ourwidth = 0;
	int foundseven = 0, foundnine = 0;

	input.open("maze.txt");
	
	if (!input)
	{
		cout << "Failed to open the input maze." << endl;
		system("PAUSE");
		exit(1);
	}

	while (true)
	{
		input.get(newchar);
		if (input.eof())
			break;

		if (newchar == '\n' || newchar == '\r')
		{
			if (!midline)
				continue; // ignore blank lines
			midline = false;
			height++;

			if (width == 0)
				width = ourwidth;
			else if (width != ourwidth)
			{
				cout << "Input maze is not a rectangle" << endl;
				system("PAUSE");
				input.close();
				free(maze);
				exit(1);
			}
			ourwidth = 0;
			continue;
		}

		if (!midline)
			midline = true;

		maze = (char *)realloc(maze, sizeof(char)* ((width * height) + ++ourwidth));
		mptr = maze + ((width * height) + ourwidth-1);

		if (newchar == '7')
			foundseven++;
		else if (newchar == '9')
			foundnine++;
		else if (newchar != ' ')
			newchar = WALL;

		*mptr = newchar;

		// Debug.
		// If you want to see the pointer magic, uncomment this.
		//printf("%c - %p (%p)\n", *mptr, mptr, maze);

		if (width != 0 && ourwidth > width)
		{
			cout << "Input maze is not a rectangle" << endl;
			system("PAUSE");
			input.close();
			free(maze);
			exit(1);
		}
	}

	input.close();

	if (midline)
	{
		if (ourwidth != width)
		{
			cout << "Input maze is not a rectangle" << endl;
			system("PAUSE");
			free(maze);
			exit(1);
		}
		else
			height++;
	}
	if (!foundseven)
	{
		cout << "Didn't find an entrance ('7')" << endl;
		system("PAUSE");
		free(maze);
		exit(1);
	}
	else if (foundseven > 1)
	{
		cout << "Found more than one entrance ('7')" << endl;
		system("PAUSE");
		free(maze);
		exit(1);
	}
	else if (!foundnine)
	{
		cout << "Didn't find an exit ('9')" << endl;
		system("PAUSE");
		free(maze);
		exit(1);
	}
	else if (foundnine > 1)
	{
		cout << "Found more than one exit ('9')" << endl;
		system("PAUSE");
		free(maze);
		exit(1);
	}
}

// Draw the final completed maze.
void draw(void)
{
	char *mptr = maze;
	ofstream output;
	int x, y;

	output.open("solved.txt");

	for (y = 0; y < height; y++)
	{
		for (x = 0; x < width; x++)
		{
			// Hide the blocked (failed) paths
			if (*mptr == BLOCKED)
				*mptr = ' ';
			cout << *mptr;
			output << *mptr;
			mptr++;
		}
		cout << endl;
		output << endl;
	}
	output.close();
}

// In the name of reducing complexity.
#define CHARUP    *(maze + ( (x  ) + ((y-1) * width) ) )
#define CHARDOWN  *(maze + ( (x  ) + ((y+1) * width) ) )
#define CHARLEFT  *(maze + ( (x-1) + ((y  ) * width) ) )
#define CHARRIGHT *(maze + ( (x+1) + ((y  ) * width) ) )

// Perform a step.
// Returns true if exit reached, false if not.
bool step(void)
{
	char *mptr;
	int x,y,loc;
	bool leftgood = true, rightgood = true, upgood = true, downgood = true;
	static int lastdirection = 0;

	// Find our seven.
	for (loc = 0; loc < width*height; loc++)
	{
		mptr = maze + loc;
		if (*mptr == '7')
			break;
	}
	if (loc >= width*height)
	{
		cout << endl << "Somehow lost the 7 while stepping through!" << endl;
		system("PAUSE");
		free(maze);
		exit(1);
		return true;
	}

	x = loc%width;
	y = loc/width;

	if (x == 0)
		leftgood = false;
	else if (x == width-1)
		rightgood = false;

	if (y == 0)
		upgood = false;
	else if (y == height-1)
		downgood = false;

	stepnum++;

	// start by looking for the exit.
	if (upgood && CHARUP == '9')
	{
		CHARUP = '7'; // Found it!
		*mptr = PATH;
		return true;
	}
	else if (downgood && CHARDOWN == '9')
	{
		CHARDOWN = '7'; // Found it!
		*mptr = PATH;
		return true;
	}
	else if (leftgood && CHARLEFT == '9')
	{
		CHARLEFT = '7'; // Found it!
		*mptr = PATH;
		return true;
	}
	else if (rightgood && CHARRIGHT == '9')
	{
		CHARRIGHT = '7'; // Found it!
		*mptr = PATH;
		return true;
	}

	// no exit! damn!
	// look for a blank then.
	if (upgood && CHARUP == ' ')
	{
		CHARUP = '7'; // Found it!
		*mptr = PATH;
		lastdirection = 1;
		return false;
	}
	else if (downgood && CHARDOWN == ' ')
	{
		CHARDOWN = '7'; // Found it!
		*mptr = PATH;
		lastdirection = 2;
		return false;
	}
	else if (leftgood && CHARLEFT == ' ')
	{
		CHARLEFT = '7'; // Found it!
		*mptr = PATH;
		lastdirection = 3;
		return false;
	}
	else if (rightgood && CHARRIGHT == ' ')
	{
		CHARRIGHT = '7'; // Found it!
		*mptr = PATH;
		lastdirection = 4;
		return false;
	}

	// no blanks? eep!
	// backtrack, look for an asterisk then.
	if (lastdirection)
	{
		// rudimentary prevention of loop screwing up
		// lastdirection should always be right
		if (lastdirection == 1) // up
			CHARDOWN = '7';
		else if (lastdirection == 2) // down
			CHARUP = '7';
		else if (lastdirection == 3) // left
			CHARRIGHT = '7';
		else //if (lastdirection == 4) // right
			CHARLEFT = '7';

		*mptr = BLOCKED;
		lastdirection = 0;
		return false;
	}
	else if (upgood && CHARUP == PATH)
	{
		CHARUP = '7'; // Found it!
		*mptr = BLOCKED;
		return false;
	}
	else if (downgood && CHARDOWN == PATH)
	{
		CHARDOWN = '7'; // Found it!
		*mptr = BLOCKED;
		return false;
	}
	else if (leftgood && CHARLEFT == PATH)
	{
		CHARLEFT = '7'; // Found it!
		*mptr = BLOCKED;
		return false;
	}
	else if (rightgood && CHARRIGHT == PATH)
	{
		CHARRIGHT = '7'; // Found it!
		*mptr = BLOCKED;
		return false;
	}

	// we're trapped?!
	cout << endl << "Maze unsolvable!" << endl;
	cout << "I got stuck at (" << x << ", " << y << ") after " << stepnum << " steps." << endl;
	system("PAUSE");
	free(maze);
	exit(1);
	return true;
}

// Main function
int main(void)
{
	char spinwheel[4] = {'-', '\\', '|', '/'};

	//Open our input file and give us a maze to work with.
	initalize();

	system("cls");
	cout << "Working! [/]\b\b";

	do
	{
		// In case it gets caught for a while.
		if (!(stepnum%100))
			cout << spinwheel[(stepnum/100)%4] << "\b";
	} while (!step());

	system("cls");
	cout << "I found the exit in " << stepnum << " steps!" << endl;
	draw();

	cout << endl << "I saved the solved maze as \"solved.txt\"." << endl;
	
	free(maze);
	system("PAUSE");
	return 0;
}

Obviously I could use structs and whatnot, but... like I said, Sunday night, two hours, while half asleep.
 
Last edited:
Testing for exit, and then testing for blank space? Why not simply test for areas which don't have a wall tile? I would have abstracted that all into a tryMove() function.
 
Code:
###########################
# HUGE GIGANTIC MESS OF A #
#      MAZE GOES HERE     #
############# #############
#                         #
######################### #
# #See how I start right# #
# # right next to the  #  #
# #        exit?     ### ##
# ####################   9#
#                      #7##
###########################

Test for exit first, save a potential headache if it turns out you're running right beside it after all.
 
Lol, C itself is way to hard for me.

The biggest code I've ever made is a code in gamemaker that allowed me to make music play in a level. The code taught me how to do it, and I had to read over the directions, like, 5-7 times before I could get it right(The ; bugs me).

And game maker may be the closest I'll ever get to C. At all.
 
Game Maker is one of the easiest languages ever. C and C++ is quite difficult and takes time and practice to learn, while in Game Maker you can just drag and drop things and in minutes your finished.

OFFTOPIC
I hope your talking about Game Maker from YoYo Games.

Chaotic Chao said:
The biggest code I've ever made is a code in gamemaker that allowed me to make music play in a level. The code taught me how to do it, and I had to read over the directions, like, 5-7 times before I could get it right(The ; bugs me).

The longest i've written is also a music code:
Code:
    if Invincibility = 0 
        {
            exit;
        }
    else
        {
            if Invincibility = 1
                {
                    if InvincibilityTimer < 5
                        {
                           sound_stop(bgmInvincibility);
                           sound_play(global.Music); 
                            
                        }
                    else
                        {
                    
                        }
                }
            else
                {
                    exit;
                }
        }
        
        
        if (Invincibility = 1 && InvincibilityTimer > 5)
        {
         if sound_isplaying(bgmInvincibility)
            {
                            
            }
            else
            {
            sound_play(bgmInvincibility);
            }
        }

Using a global function in it I can swap music tracks during lets say an Invincibility power-up, when finished, swap back to the Room's assigned track. Although it's a bit messy.

Also have you tried Visual Basics, its a good place to start learning.
 
Drag 'n' drop is not a "language". Sure, Game Maker has a scripting language, but that's not DnD.

I would strongly advise against Visual Basic and instead recommend learning Python. It teaches good coding practices, but it's also fun and can actually be used to write serious programs. That, and it frees you from being tied to Microsoft.

(On an unrelated note, I just now learned today that you can pass an int foo[] into a function and it acts like int *foo. Not sure why I didn't think this was the case, since, once again, arrays are pointers in disguise. It's still not passing by reference, though, so hah. Yes, it's still an acceptable thing to do. It's just that I don't think I've ever actually used the int foo[] syntax to pass an array into a function before.)
 
Last edited:
Here's the thing. I'm trying to make my code move in whatever the direction variable is "facing", but always try to circle around to the right whenever it can (the "right wall solution"). But my code isn't doing that; it's just zigzagging around. Here's a copy of the contents of the step() function, which is basically the heart of the navigator AI. There are some other problems with this code, and I'm sure they will be apparent to you immediately, but I just want to concentrate on making it circle around the right edge of the walls. Then I can divert my attention to the other slightly-lower priority problems.

Code:
int fill;
    display(maze);
    if(start)
    {
        i = 19;
        j = 9;
        start = false;
    }
    if(direction == 0)
    {
        if(maze[i + 1][j] == element1)
        {
            direction = 1;
            maze[i + 1][j] = 2;
            maze[i][j] = element2;
            i++;
        }
        else if(maze[i][j - 1] == element1)
        {
            direction = 2;
            maze[i][j - 1] = 2;
            maze[i][j] = element2;
            j--;
        }
        else if(maze[i - 1][j] == element1)
        {
            direction = 3;
            maze[i - 1][j] = 2;
            maze[i][j] = element2;
            i--;
        }
        else if(maze[i][j + 1] == element1)
        {
            maze[i][j + 1] = 2;
            maze[i][j] = element2;
            j++;
        }
    }
    else if(direction == 1)
    {
        if(maze[i][j - 1] == element1)
        {
            direction = 2;
            maze[i][j - 1] = 2;
            maze[i][j] = element2;
            j--;
        }
        else if(maze[i - 1][j] == element1)
        {
            direction = 3;
            maze[i - 1][j] = 2;
            maze[i][j] = element2;
            i--;
        }
        else if(maze[i][j + 1] == element1)
        {
            direction = 0;
            maze[i][j + 1] = 2;
            maze[i][j] = element2;
            j++;
        }
        else if(maze[i + 1][j] == element1)
        {
            maze[i + 1][j] = 2;
            maze[i][j] = element2;
            i++;
        }
    }
    else if(direction == 2)
    {
        if(maze[i - 1][j] == element1)
        {
            direction = 3;
            maze[i - 1][j] = 2;
            maze[i][j] = element2;
            i--;
        }
        else if(maze[i][j + 1] == element1)
        {
            direction = 0;
            maze[i][j + 1] = 2;
            maze[i][j] = element2;
            j++;
        }
        else if(maze[i + 1][j] == element1)
        {
            direction = 1;
            maze[i + 1][j] = 2;
            maze[i][j] = element2;
            i++;
        }
        else if(maze[i][j - 1] == element1)
        {
            maze[i][j - 1] = 2;
            maze[i][j] = element2;
            j--;
        }
    }
    else if(direction == 3)
    {
        if(maze[i][j + 1] == element1)
        {
            direction = 0;
            maze[i][j + 1] = 2;
            maze[i][j] = element2;
            j++;
        }
        else if(maze[i + 1][j] == element1)
        {
            direction = 1;
            maze[i + 1][j] = 2;
            maze[i][j] = element2;
            i++;
        }
        else if(maze[i][j - 1] == element1)
        {
            direction = 2;
            maze[i][j - 1] = 2;
            maze[i][j] = element2;
            j--;
        }
        else if(maze[i - 1][j] == element1)
        {
            maze[i - 1][j] = 2;
            maze[i][j] = element2;
            i--;
        }
    }
    else
    {
        fill = element2 + 1;
        element1 = element2;
        element2 = fill;
    }
 
You'd probably have an easier time if you were to create two functions:

bool testMove(int i, int j)
bool move(int i, int j)

Where i and j are local coordinates originating from your position in the maze (EG. 0, 1 would move one square down).

testMove() returns true if the space is free, and false if it is blocked (EG. contains a wall).
Note that move() should call testMove() for safety reasons before actually changing your position. move() should then return the return value of testMove().

To make your life easier, instead of having cases for every single direction and then testing every single possible move after that, it might be better to use an array to store the four possible offsets you can move to. You might find it more convenient to compare based on the relative direction to where you are facing so that you could eliminate the first level if if/else statements (I did suggest switch/case, but either way you really should remove that level altogether).

I'll let you work out the rest yourself.
 
I've changed the algorithm again, trying as best I can to follow that advice. I also made it so that the character representing the AI changes depending on what direction it is facing (right = '>', down = 'V', left = '<', up = '^'). However, there are two main problems with this algorithm that I just can't fix:

1. It still doesn't execute the right-wall method. It continues to do the zigzag thing.
2. It always turns and leaves the maze through the start! I've tried to program in exceptions to prevent this, but none of them work.

Here's the latest code:

Code:
#include <iostream>
#include <Windows.h>
#include <conio.h>
#include <cstdlib>
#define _WIN32_WINNT 0x0500
using namespace std;
enum Colors{blue=1, green, cyan, red, purple, yellow, grey, dgrey, hblue, hgreen, hred, hpurple, hyellow, hwhite};

//global variables
int maze[20][20];        //the matrix for the maze itself
int i, j;                //maze counters
int xpos, ypos;            //position of the AI in the maze
int direction = 0;        //direction of the AI
int wait;                //pause counter

//function prototypes
void coutc(int color, char*output);
void generate();
void display();
void step(int &direction);
void move(int x, int y);
bool moveIsPossible(int x, int y);
int restart();

///initializes the program and calls the other functions
int main()
{
    //initialization
    cout << "Welcome to Maze Navigator!" << endl << endl;
    system("pause");
    generate();
    //loop to generate each frame of the maze
    while (maze[0][10] != 2)
    {
        //generates a frame
        step(direction);
        //pauses before generating the next frame
        for (wait = 0; wait < 20000000; wait++);
    }

    //displays upon maze completion
    system("cls");
    coutc(grey, "Maze Solved!");
    restart();
}

///outputs a value with a specified text color
void coutc(int color, char* output)
{
   HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
   SetConsoleTextAttribute(handle, color);
   cout << output;
   SetConsoleTextAttribute(handle, color);
}

///generates a randomly structured maze
void generate()
{
    int spaceFreq;
    srand(GetTickCount());
    system("cls");
    cout << "Enter a space frequency between 1 and 10: ";
    cin >> spaceFreq;
    spaceFreq++;
    //checks whether the chosen space frequency is valid
    if(spaceFreq < 2 || spaceFreq > 10)
    {
        system("cls");
        cout << "Error: Invalid space frequency!" << endl << endl;
        system("pause"); system("cls");
        main();
    }
    //builds a randomized maze based on the chosen space frequency
    for(i = 0; i < 20; i++)
    {
        for(j = 0; j < 20; j++)
        {
            maze[i][j] = rand() % spaceFreq + 1;
            if(maze[i][j] != 0 && maze[i][j] != 1) maze[i][j] = 0;
        }
    }
    //ensures the edges of the maze are solid
    for(i = 0; i < 20; i++)
    {
        for(j = 0; j < 20; j++)
        {
            maze[0][j] = 1;
            maze[19][j] = 1;
            maze[i][0] = 1;
            maze[i][19] = 1;
        }
    }
    maze[19][9] = 2;        //sets start point
    maze[0][10] = 0;    //sets exit point
    maze[18][9] = 0;    //sets start point opening
    maze[1][10] = 0;    //sets exit point opening
    xpos = 9;            //initializes AI x position
    ypos = 19;            //initializes AI y position
}

///displays the maze on the console
void display()
{
    system("cls");
    cout << endl;
    coutc(hgreen, "                                       $");
    cout << endl;
    for(int i = 0; i < 20; i++)
    {
        cout << "                  ";
        //specifies the characters corresponding to different components of the maze
        for(int j = 0; j < 20; j++)
        {
            switch(maze[i][j])
            {
                case 0: coutc(blue, "  "); break;                                //empty space
                case 1: coutc(green, " X"); break;                                //solid wall
                case 2:
                    {
                        if(direction == 0){coutc(hblue, " >"); break;}            //AI facing right
                        else if(direction == 1){coutc(hblue, " V"); break;}        //AI facing down
                        else if(direction == 2){coutc(hblue, " <"); break;}        //AI facing left
                        else if(direction == 3){coutc(hblue, " ^"); break;}        //AI facing up
                    }
                case 3: coutc(blue, " '"); break;                                //path marker
                case 4: coutc(blue, " *"); break;                                //repeated path marker
                default: cout << "  " << maze[i][j];                            //default component
            }
        }
        cout << endl;
    }
    coutc(hred, "                                     @");
}

///AI to make the character move through the maze
void step(int &direction)
{
    display();
    switch(direction)
    {
        case 0:
            direction = 1;
            moveIsPossible(0, 1);
            if(moveIsPossible(0, 1)){move(0, 1); break;}
        case 1:
            direction = 2;
            moveIsPossible(1, 0);
            if(moveIsPossible(1, 0)){move(1, 0); break;}
        case 2:
            direction = 3;
            moveIsPossible(0, -1);
            if(moveIsPossible(0, -1)){move(0, -1); break;}
        case 3:
            direction = 0;
            moveIsPossible(-1, 0);
            if(moveIsPossible(-1, 0)){move(-1, 0); break;}
        default: direction = 0;
    }
}

///moves the AI through the maze
void move(int x, int y)
{
    maze[ypos + x][xpos + y] = 2;
    maze[ypos][xpos] = 3;
    ypos = ypos + x;
    xpos = xpos + y;
}

///checks to see if a move is possible
bool moveIsPossible(int x, int y)
{
    if(maze[ypos + x][xpos + y] != 0) return false;
    else if(ypos == 19 && direction == 1) return false;
    else return true;
}

///program exits or restarts depending on user input
int restart()
{
    int choice;
    cout << endl << "Do you want to run another maze? (1/0)" << endl;
    cin >> choice;
    switch(choice)
    {
        case 0: return 0; break;
        case 1: system("cls"); return main(); break;
        default: return 0;
    }
}
 
Last edited:
I would do some more bugtesting on moveIsPossible(). You're sorta mixing x and y around in ways that is sort of counter-intuitive from a code-readability standpoint.

Or maybe you could just replace ypos + x with ypos + y and etc.

Once moveIsPossible() works, remove the special case you used to attempt blocking the marker from leaving the maze. If moveIsPossible() worked in the first place you wouldn't need to do a special case.
 
Last edited:
Well, yesterday morning I officially got the homework assignment to create a maze algorithm. This experience actually did a pretty good job of preparing me for it; the program my professor wanted me to write was in many ways considerably less complicated than what I was trying to do here (as a matter of fact, the algorithm I produced is actually superior to the one that was suggested by the TA). It's still primitive by your standards, but it gets the job done quite well. I've already more or less perfected the algorithm, with 2 weeks to spare. I'd post it up here to show you, but I don't think I should be distributing my actual homework projects online.

Anyway, thank you guys. I may not have been able to follow all of your advice, but you did point me in the right direction.
 
Okay, now I'm in much worse confusion. I have a new problem with an assignment

Code:
#include "student.h"
#include "course.h"
#define SHOW_STUDENT
#define SHOW_COURSE

struct data {
    string name;
    string course;
    int grade;
};

int main() {
    vector <data> contents;
    ifstream list;
    list.open("grades.csv");
    if(!list.is_open()) {
        cout << "Error: could not open file!" << endl;
    }
    while(!list.eof()) {
        [U][B]contents.name =[/B][/U]
    }
}
The underlined part is the problem. It breaks the code. I get compiler errors claiming that "name" doesn't exist.

How the heck am I supposed to create a vector of structs? The two types of structures are ambiguous together!
 
Last edited:
Of course it doesn't exist. Remember that C++ vectors are fairly similar to (but not quite like) C arrays, so you need to give the index. Something along the lines of contents[index].name...
 
Okay, here's what I'm trying to do. I want to read in a CSV file with an undetermined number of lines and three values per line, two of which are strings and one which is a char. And I want it to be read into the vector of structs "contents", such that the first string on a line "i" becomes the value of contents.name, the second string becomes the value of contents.course, and the character is the value of contents.grade. (Actually, the only way I got my current version to compile was by turning every one of those into arrays of characters, and I would also like to get rid of that problem.)

You guys probably shouldn't actually post code for me, because this is an actual assignment which I will be graded on, but I'd really appreciate it if you could explain the best way to do it.

The best I could do was this, but it doesn't work. Why isn't it working?\

Code:
#include "student.h"
#include "course.h"
#define SHOW_STUDENT
#define SHOW_COURSE

struct data {
public:
    char name[100];
    char course[100];
    char grade[100];
};

int main() {
    vector <data> contents;
    data new_data;
    int type = 1;
    int i = 0;
    ifstream list;
    list.open("grades.csv");
    if(!list.is_open()) {
        cout << "Error: could not open file!" << endl;
    }
    else {
        while(!list.eof()) {
            if(type == 1) {
                std::cin.getline(new_data.name, 100, ',');
                cout << new_data.name;
                type++;
            }
            else if(type == 2) {
                std::cin.getline(new_data.course, 100, ',');
                cout << new_data.course;
                type++;
            }
            else if(type == 3) {
                std::cin.getline(new_data.grade, 100, ',');
                contents.push_back(new_data);
                cout << new_data.name;
                type = 1;
                i++;
                cout << endl;
            }
        }
        cout << "The number of records found is " << contents.size();
    }
}
 
Last edited:
*Trying to get something amongst all this patavina*
Well, saturday I'll have a C++ class and I will ask my teacher why this code doesn't work.
This thing of cout/cin just doesn't fit on my mind, and there are some things on this program that I don't know yet.
 
I'd like to know the answer, too...that looks confusing as hell. I'd say something about using FILE* and fgets/fgetc/feof but Blitzzo would probably slap me.
 
I have, through the use of an extremely brute-force algorithm, managed to solve that particular problem. However, I have another frustrating obstacle now. How do I remove any duplicate elements from a vector of strings?
 
Status
Not open for further replies.

Who is viewing this thread (Total: 0, Members: 0, Guests: 0)

Back
Top