473,326 Members | 2,104 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Getting program input from command line or user interface and mapping strings in C

4
Hi this is my first post!
I'm currently learning C programming language and have just finished structure section. At this point I think I'm able to program some very basic text command line games. However the truth is I already see some technical difficulties at the planning level. I wish there are some relatively simple solutions to my problems and here they are:
1. I want to make this game under one command line enviroment with some commands. For example /equip whateversword to call item/weapon/armor function to ajust corresponding attributes or hp/mps. I learned a little bit about the argc and argv and couldn't yet do anything with them.
2. If the above option is too complicated I can use question/answer format for all the commands but I'm have some serious problem with scanf function. Sometimes it behaves weirdly at output level. Is there a better function to use for such problems?
3. Is there a way to generate an item ID so that the item number in the item array will link to the actual item char string variable.

Thank you very much!!
Oct 16 '07 #1
9 2614
Ganon11
3,652 Expert 2GB
3. Is there a way to generate an item ID so that the item number in the item array will link to the actual item char string variable.
Interesting that you would think of this. You've actually just thought of the basic concept behind a Map data structure (Or possibly Hashing?). I'm not sure if it's possible in C, though, as my experience is with C++.

You might be able to create a const array of items, and keep track of which item at which index is which, so when you need to retrieve "short sword," you know it's in slot 4 of itemArray (or whatever).
Oct 16 '07 #2
weaknessforcats
9,208 Expert Mod 8TB
I learned a little bit about the argc and argv and couldn't yet do anything with them.
argc is the number of strings in the argv array. argv[0] is always the program name. For example:

Expand|Select|Wrap|Line Numbers
  1. % game.exe  swords shield
  2.  
Here argc will be 3.
argv[0] contains "game.exe"
argv[1] contains "swords"
argv[2] cotains "shield"

...but I'm have some serious problem with scanf function.
Sometimes it behaves weirdly at output level.
I should think so since scanf is an input function.

Just be sure you use the address of the variable to scanf into and be sure the type or that variable matches the data being scanned.

scanf will skip all whitespace so it doesn't wortk well for strings with multiple words. Here you would use gets().
Oct 16 '07 #3
bu0461
4
Hi thanks for the reply!
I think I was thinking about as user inputs a string say "short sword", there is no way to link this string with item number since I can't put *char=item[y].
I could make a itemID array for ID and itemNumber for amount of item and asign 2 pointers for simuteneous manipulation but I couldn't think of other way to link user input with itemID and itemNumber except for a whole buch of if statements.
Oct 16 '07 #4
Banfa
9,065 Expert Mod 8TB
bu0461 - I have changed the title of your thread, we ask people to us meaningful titles (we know you had a question, otherwise you would not have posted here) as it is better for ratings on Google etc.

You can find out about this in our posting guidelines.


Ganon/weaknessforcats, tut, tut, as moderators you both should have picked this up :7
Oct 16 '07 #5
bu0461
4
argc is the number of strings in the argv array. argv[0] is always the program name. For example:

Expand|Select|Wrap|Line Numbers
  1. % game.exe  swords shield
  2.  
Here argc will be 3.
argv[0] contains "game.exe"
argv[1] contains "swords"
argv[2] cotains "shield"
Hi thanks for the reply!
I guess it'll probably be too difficult to use command mode. I'll stick with the basic input mode.

Just a side question: is there a way to control the timing of the outputs? For example when I display mob hitting character, I want it to display 1st line and 2nd line after 1 second and so on.
Oct 16 '07 #6
Banfa
9,065 Expert Mod 8TB
bu0461, it sounds like you are trying to create a user interface.

The first thing to realise is that it is unlikely that you will be creating (as one of your first projects anyway) a program where you type commands into you computers user interface and the program runs and performs some in game action and exits.

This would imply that there was another application running in the background controlling the game and that you where using inter-process communications to send it message/commands. I get the impression that you may not be ready for that.

What you can do is create your own command line interface for your program. That is you start the game and it displays a prompt that you can type commands into it. This is the classic text based advernture game that was popular a decade or so ago.

I would not be using scanf because your different command will probably require different parameters, you will not be able to tell before the command is entered what the parameters to scanf should be. Additionally scanf is consider to be a rather unsafe function nowa-days and it is worth not getting in the habit of using it. I would use fgets, this allows input to a text buffer of a specified length of everything the user types.

Once you have the users command in a buffer you can then parse it, there are a number of ways to do this you could use sscanf or strtok, sscanf gets round the issues that effect scanf because it works on a string not user input and you know how long the string is. strtok is not a very good function and I wouldn't recommend it particularly. You could also just parse the data yourself using pointers and other less complex functions (strcmp, strtoul etc).

I think my approach to this would be to have a function that splits off the first token (word) of the input, compares it to a list of valid commands and then if valid calls a different function for each command with the rest of the input line. The function then verifies the rest of the input to the command and actions it before returning to request the next command.

In fact to make addition of commands easy I would probably make all command handlers have the same function prototype and then implement a table contains command string and handler function so that adding new commands is just writing the function and adding entries to the table.
Oct 16 '07 #7
Banfa
9,065 Expert Mod 8TB
Just a side question: is there a way to control the timing of the outputs? For example when I display mob hitting character, I want it to display 1st line and 2nd line after 1 second and so on.
If you are using Windows look up the function Sleep

If you are using Linux look up the function sleep

If you are using something else check your platform documentation.
Oct 16 '07 #8
bu0461
4
Thank you Banfa but I don't quite get the fget function and the whole process.
But I got your idea and I'll rush to the disk file section!
Oct 16 '07 #9
Banfa
9,065 Expert Mod 8TB
So have you heard of the function gets
Expand|Select|Wrap|Line Numbers
  1. char *gets( 
  2.    char *buffer 
  3. );
returns a string from the keyboard, but it does not put a check on the length of the string. Try this program
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int main(int, char *[])
  4. {
  5.     char hw1[] = "Hello World!";
  6.     char input[5];
  7.     char hw2[] = "Hello World!";
  8.  
  9.     gets(input);
  10.  
  11.     puts(hw1);
  12.     puts(input);
  13.     puts(hw2);
  14.  
  15.     return 0;
  16. }
when it runs you have to input data, first time you run it just enter 2 or 3 characters, it will appear to work. Then run it again and input more characters and keep going inputting more and more.

Various things will happen depending on your platform and compiler options but what you might see is that with 2 or 3 characters it appears to work, with a few more the hw1 and/or hw2 strings get over written and with a lot more the program crashes.

This is a buffer overrun error (an exploit often used by hackers if left in code) the gets function does not stop you writing more string to the pointer it receives than there is room for so when you input 10 characters (say) it just merrily stamps over the data around the input variable.

Step forward the fgets function
Expand|Select|Wrap|Line Numbers
  1. char *fgets( 
  2.    char *str,
  3.    int n,
  4.    FILE *stream 
  5. );
This function takes a length of buffer as well as a pointer, it guarantees not to write more data to the pointer than you tell it is available via the parameter n.

But it takes a FILE * surely it works on a file input stream? Well yes it does however the standard input, standard output and standard error are file streams and can be accessed as such. You don't have to open them they are automatically opened for you all you have to do is use their identifiers

stdin - for standard input - input stream
stdout - for standard output - output stream
stderr - for standard error - output stream

declared in stdio.h. Modifying the code to use fgets it becomes

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int main(int, char *[])
  4. {
  5.     char hw1[] = "Hello World!";
  6.     char input[5];
  7.     char hw2[] = "Hello World!";
  8.  
  9.     fgets(input, sizeof input, stdin);
  10.  
  11.     puts(hw1);
  12.     puts(input);
  13.     puts(hw2);
  14.  
  15.     return 0;
  16. }
Now when you run the program it does not matter how much data you input, not more than 5 characters (the last one being '\0') are written to input and the program does not crash.
Oct 16 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: christopher diggins | last post by:
I am wondering if any can point me to any open-source library with program objects for C++ like there is in Java? I would like to be able to write things like MyProgram1 >> MyProgram2 >>...
2
by: SunRise | last post by:
Hi I am creating a C Program , to extract only-Printable-characters from a file ( any type of file) and display them. OS: Windows-XP Ple help me to fix the Errors & Warnings and explain...
4
by: Sean Shanny | last post by:
To all, Running into an out of memory error on our data warehouse server. This occurs only with our data from the 'September' section of a large fact table. The exact same query running over...
3
by: dei3cmix | last post by:
Hey, I am having a problem with a program I am working on. Basically, the first part of the program gets input from a file using cin.getline. Then the second part, (still in the same main as the...
4
by: Byte | last post by:
The following code will not work for me: x = 1 while x == 1: print 'hello' x = input('What is x now?: ') while x == 2: print 'hello again'
1
by: Kayvine | last post by:
Hi guys, this is a question I have for an assignment, it is pretty long, but I am not asking for the code(well if someone wants to write I'll be really happy, lol), but I just want to know how to...
6
by: =?iso-8859-1?q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
Usually someone writes a program and guarantees its behaviour so long as people don't deliberately go and try to make it malfunction. For instance, let's say we have a "Proceed" button on the...
7
by: Jwe | last post by:
Hi, I've written a program which has both a command line interface and Windows form interface, however it isn't quite working correctly. When run from command line with no arguments it should...
0
amitpatel66
by: amitpatel66 | last post by:
There is always a requirement that in Oracle Applications, the Concurrent Program need to be execute programatically based on certain conditions/validations: Concurrent programs can be executed...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.