473,608 Members | 2,077 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

4 New Member
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 2630
Ganon11
3,652 Recognized Expert Specialist
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 Recognized Expert Moderator Expert
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 New Member
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 Recognized Expert Moderator Expert
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 New Member
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 Recognized Expert Moderator Expert
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 Recognized Expert Moderator Expert
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 New Member
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 Recognized Expert Moderator Expert
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
2594
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 >> Fork(MyProgram3, SomeFile); If not would this be something of interest to others? Thanks in advance,
2
4186
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 how to use Command-Line Arguments inside C program.
4
5988
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 data from August or any prior month for that matter works fine which is why this is so weird. Note that June 2004 through today is stored in the same f_pageviews table. Nothing has changed on the server in the last couple of months. I upgraded...
3
3683
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 first part) needs to get input from the user, and I want to do this with cin.getline also. The problem I am getting, is when I run the program, the text if read in from the file correctly, but it seems to just skip over the cin.getline when I want...
4
1606
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
2508
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 start it and what main topics in C I will need to cover in the assignment. Thanks a lot. CSC180 Assignment #3: Menu Madness Due Date: Thursday, November 8th at 1:00am Contents: · General Info · What to Hand In o Submission Instructions
6
1500
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 dialog box, but that this button is greyed out because the user hasn't entered their username yet. Now let's say the user writes some code that sends a message to the dialog box to enable the "Proceed" button even tho the programmer didn't design...
7
9353
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 display the Windows form. The form is being displayed but the command only returns when the form is closed. I want the command line to return immediately, leaving the form displayed.
0
13315
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 programatically either from UNIX or Oracle PLSQL. In this Section, I will be explaining about calling a Concurrent program from UNIX using the CONCSUB Command. Pre-requisite: 1. Concurrent Program should be registered in oracle Applications...
0
8063
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8003
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8498
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8478
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8341
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6817
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6014
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3962
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1598
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.