I am trying to make a game similar to chess. I want the user to type in what position of the piece they want to move is, then were they want to move it... ( on an 8x8 grid - A1 through to H8)
I cant workout a simple way to find a variable from what the user has typed in. The code I currently have is:
void main() {
printf("Enter Piece to Move: ");
scanf("%s",&move);
printf("\n\nWhere would you like to move %s?:",move);
scanf("%s",&to);
[...]
What i also have is a variable list of all the location of pieces. What I would like to happen is, if the user was to enter A1 for the piece to move. I want the value of variable named A1 to be used. This is so I can have the current position of the piece and also what is in the place...
Hope this makes scene and someone can help :)
Take a look at the concept of arrays. If you have a 2-dimensional array, you just need to convert the letter 'A' to a number and use it as in index in the array.
You cannot refer to a variable if you dynamically obtain its name. There's just no way to do it in C, unlike, say, PHP.
You should do the mapping manually
int a[8][8];
char c1, c2;
scanf("%c%c", &c1, &c2);
a[c1-'a'][c2-'1'] = ???; //this is your variable
The above is almost a pseudocode. I mean, you should take care of bad inputs and many other things, but you should get the idea.
That is impossible in C. When your program is running the names of the variables don't exist anymore, they only exist in your code.
Instead you should be using something called an array. It would take far too long to explain here, I think you should read a book on C.
you should use 2 "holders" of your data, a board representation AND pieces positions like
enum {WKING=1,BKING,WPAWN,BPAWN,WQUEEN,BQUEEN,WBISHOP,BBISHOP,WKNIGHT,BKNIGHT,WROOK,BROOK};
int board[8*8];
/* positions: */
int wking,wqueen[9],wbishop[10],wknight[10],wrook[10],wpawn[8];
int sking,squeen[9],sbishop[10],sknight[10],srook[10],spawn[8];
...
setposFromTo(int piece,int from,int to) {
switch(piece) { case WKING: "set board AND position here" break; ... }}
Related
I'm developing a program that asks you how many disciplines you have. Next it ask the name and the grade of each;
First asks how many disciplines, and after:
printf("\nInsira o nÂș de disciplinas: ");
scanf("%i", &NDISCIPLINAS);
for(i=0;i<=NDISCIPLINAS;i++)
{
puts("Name of discipline: ");
scanf("%s", disciplina);
printf("Grade: \n");
scanf("%d", ¬as);
}
But It's not that what I really want.
I want the program to save each discipline and grade into a different variable.
Cause then I will want to fprintf the info to a specific file and it would be more easier if the info is well gathered.
My real question is basically:
IF i have 5 disciplines,how can I display the name and the grade of each,line by line, into a file?
thanks guys really strugglin' here
There are numerous ways, you can achieve your goal. I'll suggest you the three of them, which are popping in my mind right now:
Use 2 character arrays, scan values and then store them into the file. Then reuse them (using sentinel loop).
Use a dynamic structure array, which contains two members in it(Name, Grade), and use any function store(name, grade) to store values.
Get the no. of disciplines from the user in any int variable, then using a loop, get value from the user and store it directly to the file, within the loop.
edit for simplicity at the bottom
I've got a little problem in my current school project. (plain c)
The project itself is a little quiz inside a console, and I'm trying to store the questions, their answers and assigned points.
The file i want to store it in, already has text in it which will be scanned through for its total number of lines, and then will be completely wiped and written to again.
This is the File itself should look at the end:
1#Excel?#Good#Bad#Miserable#Awesome#1#5
2#Word?#Good#Bad#Miserable#Awesome#1#10
3#Powerpoint?#Good#Bad#Miserable#Awesome#4#15
(Number of the Question, the Question itself, 4 answers, the number of the right answer, and the assigned points)
The variables themselves are like this (I'll just show one for simplicity, they all are the same type)
char frageinhalt[255][255];
there are two more variables in my code below, (lines & i) those are both simple integers. lines is the total amount of lines the existing file has (reduced by one in the code below, because the last line is empty).
This char array holds the Questions themselves,
frageinhalt[0] = "Excel?"
frageinhalt[1] = "Word?"
and so on.
and this is how i want to store it
for(i=0; i<lines-1; i++) {
fprintf(datei_ptr, "%i#%s\n",i+1,frageinhalt[i]);
}
What's the problem with this?
Or is there a way to access and edit a specific line inside a file (in plain c) which I don't know of?
#########edit#########
to explain it simply (well atleast let me try):
I've got a variable
char frageinhalt[255][255];
which contains simple sentences (lets say 10) like
What is the capital of Germany?
I now want to write these sentences (in addition to an ID) into a .txt file, each sentence in its own line, like this:
1#What is the capital of Germany?
2#What is the capital of France?
This is the code i tried:
for(i=0; i=10; i++) {
fprintf(filepointer, "%i#%s\n",i+1,frageinhalt[i]);
}
but it doesn't work. Why? And how can I fix it?
I am currently working on a C project that requires the creation, storage and mathematical usage of numbers that are too large to be put into normal variable types. To do this, we were instructed to represent numbers as a sequence of digits stored in an array of integers. I use a struct defined as so:
struct BigInt {
int val[300000];
int size;
};
(I know I can dynamically allocate memory, and that that is
preferable, however this is how I am most comfortable doing it, it has
worked perfectly fine so far and this is how the professor instructed us to do it.)
I then define member A:
struct BigInt A={NULL};
I can generate and store, then add, subtract and multiply random numbers with this, and they can have any number digits up to 300000(far more than I will ever need to account for). For example, if the number 1432 was generated and stored into BigInt A, A.size would be 4 and A.val[2] would be 3.
Now I need to create a way to store user input into this type. For example, the user needs to be able go straight from inputting 50! and then it be stored into this struct array type I have created. How would I go about doing this?
The only ways that I could think of would be to store the user input as a string then have the math in that string be executed multiple times, each time storing a different digit, or reading numbers straight off of stdout, but I don't know if either of those are even possible or would solve my problem.
You can try using string as follows:
char s[300001];
scanf("%s", s);
A.size = strlen(s);
for(int i = 0; i < A.size; i++){
A.val[i] = s[i] - '0';
}
I think it will solve your problem, but this way of implementation for big integers is not efficient though.
Sorry for previous answer, to solve in c you need to use array of chars to store each digits.
I'm trying to create a text adventure game that 7 rooms, with the information saved in files. This question IS similar to Connect Rooms Randomly in Adventure Game however the answer didn't exactly help me. I've gone about my program in a different way than that OP so I'm not sure how to use that answer to help me.
The idea is you have 7 rooms, named say A, B, C, D, E, F, and G. After the rooms are created, I need to randomly connect them to each other. Each room needs between 3 and 6 random connections. If room A is connected to B, C, and D, each of those rooms should be connected to A. This information is then saved to a file which is read later.
The code I have for this section so far is:
char *connections[7];
int j = 0;
int randomRoom;
for (j = 0; j <= randConnections; j++) {
randomRoom = rand() % 10;
if (randomRoom == randName) {
randomRoom = rand() % 10;
} else {
connections[j] = names[randomRoom];
}
randConnections is a random int between 3 and 6, defined earlier in the code. names is a string array that holds the names of the rooms, also defined earlier in my program.
I am pretty new to C (I'm mostly experienced with Java) so I can't figure it out. I should mention, this is all in one function defined as:
void createRooms(FILE *fp)
I know there are probably more efficient ways to do this, but at this point I'm just trying to get the code working and deal with efficiency later.
I've done a ton of googling and am honestly beating my head against the wall right now. Any help would be greatly appreciated. If there's any more code I should post or any other information let me know.
C-style strings can get a bit confusing. A "string" in pure C is a char array. Arrays in C are strongly related to pointers. In fact, instead of defining
char myCString[6] = "hello";
You could define
char * myCString = "hello";
In fact, in the first case, myCString used alone will just return a pointer to the first element. The [] operator is just a convenient dereference and increment operator. So &(myCString+1) becomes myCString[1]
So long story short, your "string" array in C is really an array of char* - pointers to the first element of an array of characters
You're trying to assign this to a single character, which doesn't make logical sense. If you mean for the connections to truly be strings, do like kcraigie says.
Here's some backup I found, I'm afraid there are more nuances and I'm not an expert, but that's the gist - https://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays#Pointers_and_Arrays
This may seem absurd coming from java - that's C for ya. C++'s standard library includes a string construct like what you'd be familiar with. It's a class that wraps a "raw" C array and controls access to it and manages it like Java and C# strings. Modern C++ best practices try to stay away from the raw arrays. You'll also notice that nothing stops you from calling MyCString[4000], which is just going to grab a piece of memory from the middle of nowhere and do heaven knows what. There is no bounds checking on raw arrays in C. Be careful!
I have an array of 20 items long and I would like to make them an output so I can input it into another program.
pos = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,]
I would like to use this as inputs for another program
function [lowest1, lowest2, highest1, highest2, pos(1), pos(2),... pos(20)]
I tried this and it does not work is there another way to do this?
I'm a little confused why you'd want to do that. Why would you want 20 outputs when you could just return pos as a single output containing 20 elements?
However, that said, you can use the specially named variable varargout as the last output variable, and assign a cell to it, and the elements of the cell will be expanded into outputs of the function. Here's an example:
function [lowest1, lowest2, highest1, highest2, varargout] = myfun
% First set lowest1, lowest2, highest1, highest2, and pos here, then:
varargout = num2cell(pos);
If what you're trying to do is re-arrange your array to pass it to another Matlab function, here it is.
As one variable:
s=unique(pos);
q=[s(1) s(2) s(end-1) s(end) pos];
otherFunction(q);
As 24 variables:
s=unique(pos); otherFunction(s(1), s(2), s(end-1), s(end), pos(1), pos(2), pos(3), pos(4), pos(5), pos(6), pos(7), pos(8), pos(9), pos(10), pos(11), pos(12), pos(13), pos(14), pos(15), pos(16), pos(17), pos(18), pos(19), pos(20));
I strongly recommend the first alternative.
Here are two examples of how to work with this single variable. You can still access all of its parts.
Example 1: Take the mean of all of its parts.
function otherFunction(varargin)
myVar=cell2mat(varargin);
mean(myVar)
end
Example 2: Separate the variable into its component parts. In our case creates 24 variables named 'var1' to 'var24' in your workspace.
function otherFunction(varargin)
for i=1:nargin,
assignin('base',['var' num2str(i)],varargin{i});
end
end
Hope this helps.
Consider using a structure in order to return that many values from a function. Carefully chosen field names make the "return value" self declarative.
function s = sab(a,b)
s.a = a;
s.b = b;