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?
Related
I'll make this short. I really want to learn from the answer. I am not here to make anyone code for me, so you choose if you want to learn me how to solve this problem or simply write the whole code.
I am trying to make a script which can read a CSV with this pattern:
DATE,TEXT,EXPENSE or INCOME,BALANCE,STATUS,DENIED.
Example: 11.01.2011,Grocery shop, -200, 700, Done, No.
I want the output to be the sum of all the expenses and income and second output what the balance is. I would like this info to be stored somewhere in the CSV file, so when I open it with excel it's there.
If you are able to explain what each line does it would be great for me so I can learn as a coding noob, but if not that's all good.
If this question is already answered I am so sorry. I have tried for a couple hours to find a answer, but I have only gotten some code that I don't know how to modify to what I want to do.
For any problem like this, I prefer to do it as a loop, structured in several parts:
read lines of text
when there are no more lines, we're done
for each line, break it into a number of fields
finally, do something interesting with the fields
The basic C function for step 1 is the fgets function. It's customery to bundle step 1 and step 2 together in the header of a while loop:
char linebuf[100];
while(fgets(linebuf, sizeof(linebuf), infp) != NULL) {
step 3; step 4;
}
Now, in the body of the loop, we have a line of text linebuf we've just read, and it's time to break it up into fields, in this case by searching for comma characters as delimiters. One way to do this sort of thing is using the library function strtok. Another is described in this chapter of some programming notes.
For files with columns of data, I like to store the broken-out fields in an array of pointers:
char *fields[MAXCOLS];
So then, you can use ordinary string operations to do interesting things with the columns (remembering that arrays in C are 0-based).
For example, to see if column 3 is the word "yes" or something else:
if(strcmp(fields[2], "yes") == 0) {
/* column 3 was "yes" */ ;
} else {
/* column 3 was something else */ ;
}
If column 5 was an amount, convert it to a number so you can do something with it:
double amount, running_total;
/* ... */
amount = atof(4);
running_total += amount;
(But beware: types float or double are not always good for dealing with monetary amounts, due to roundoff issues.)
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'm a c++ programmer and I'm having some issue with managed array. I'll explain what i mean. I'm using Visual Studio to code a Windows Form to handle a device.
I need to plot datas from a MCU connected to my PC thru a serial port. To save the values incoming from serial port, I'm using an array like that:
array<double, 1>^ datas = gcnew array<double, 1>(ndatas);
array<Byte, 1>^ byteDatas = gcnew array<Byte, 1>(2*ndatas);
where ndatas is the number of values of my series and byteDatas is the array where I will save the bytes that compose every value. Every value is made by 2 bytes.
After that, I will fill this array like this:
for(int i = 0; <=ndatas; ) {
if(bytes = serialPort1->BytesToRead>=2) {
datas[i] = getData(serialPort1, byteDatas, i);
}
i++;
}
The funcion getData is this one:
double getData(serialPort^ sp, array<Byte,1> data, int i) {
union Level {
char L[2];
signed short level;
} lvl;
sp->Read(data, i, 2);
for(int j = 0; j<=2; j++) {
lvl.L[j]= data[i+j];
}
return safe_cast<double>(lvl.level/100.00);
}
This function is on another .cpp file, so I had to use the variable SerialPort.
Everything goes like charm. If I try to use a MessageBox to display my datas, I can see how my array is correctly filled with the right values.
My next step to do, is to plot this data on a pictureBox using drawLine. But I really can't cause half of the values of the array datas are set to 0. For istance, if my series has 100 values, I can draw only the first values with the right amplitude. The other are represented, of course, as a horizontal line of zeroes.
To find this out, I have used a for cycle like that.
for(int i = 0; i<=datas->Length; i++) {
MessageBox::Show(Convert::ToString(datas[i]+" " + Convert::ToString(i+1));
}
just to be sure from when I will find the problem.
The strange part of this one is that, if I put the same MessageBox line of code under
datas[i] = getData(serialPort1, byteDatas, i);
I can display all of values without zeroes.
I'm stuck, and I don't know how to get rid of this problem. I hope I can find a little help to overcome this annoying issue.
I wish everything is crystal clear and I would like to thank everyone will give me a feedback.
Cheers,
Emiliano
When you do call getData, you're getting a valid value.
But BytesToRead goes down as you read data. At some point it drops below 2, and the rest of the for loop does nothing.
You might need to save where you are in the array when you run out of data, and when more serial data arrives, continue filling in the array from where you left off.
Plus, of course, right now you appear to be putting every data value into element 0 of the array, because you never increment i.
Also, you're reading each data point at index i, which means that you overwrite the second byte from the previous sample.
There's no need for safe_cast, the result of the division is already a double. And even if you needed a conversion, safe_cast isn't appropriate, since none of these data types are polymorphic.
Furthermore, your use of the union causes undefined behavior.
Finally, you're in C++. So why are you using what is probably the worst designed serial port API Microsoft ever made? This is C++. Calling Win32 APIs is easy, just #include <windows.h> and go, no p/invoke needed.
The title is probably not accurate but I hope that reading this post you can understand what I want to do.
I'm kind stuck in here. New in Java ME, that unfortunately has, as you know, reduced methods than the Java SE.
What I want to accomplish is this: I have a txt, with numbers in it separated by space.
I want to put them in an array that can ""behave as an usual array in c++"" when one gets numbers separated by space into an array.
Now in J2ME what I've done (using Netbeans) is: I took the txt to a stream. Later sent the stream to a byte array and finally i converted it to a char array.
Let's say the original txt was: 98 2 12 13
Part of the code is:
InputStream is = getClass().getResourceAsStream("models.txt");
try{
int st_pk1_len = is.available();
byte st_pk1[] = new byte[st_pk1_len];
is.read(st_pk1);
char st_pk1_char[] = new String(st_pk1).toCharArray();
System.out.println(st_pk1_char);
What I get printed is: 98 2 12 13
Although, my problem is that when I want to access index 0 I get only the number 9 and not 98. If I try to reach the number 12, I put the pointer to 3 but what I get is an empty space and so on.
I've searched and tried different methods that I've found without luck to convert that into the original numbers again.
It could be a stupid mistake from my side or something that I've haven't think of.
Isn't there a simple solution to this problem?
update It's working now! Array is working as a "regular"c++ char array. In case somebody else need it or have my same problem, here is how it looks like:
InputStream is = getClass().getResourceAsStream("st_pk1.txt");
int st_pk1_len = is.available();
byte st_pk1[] = new byte[st_pk1_len];
is.read(st_pk1);
char st_pk1_char[] = new String(st_pk1).toCharArray();
String PreSplitted = new String(st_pk1);
String AftSplit[] = Split(PreSplitted, " ");
If you want to check: System.out.println(AftSplit[n]);
For the split method I used the second link in the Gnat's post.
Split text in J2ME
You can treat the char array as String, containing tokens separated by space: new String(st_pk1) does that for you.
After that, you need to split it, like as described in couple other Stack Overflow questions:
How do I split strings in J2ME?
Split text in J2ME
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; ... }}