• 0

c++ input screening


Question

im trying to write a fairly simple program where the computer randomly chooses a number between 1-100, and the user trys to guess it in 7 go's. I can do it alright, but if i accidently entered a letter instead of a number for my guess, it went completly spastic. I need help trying to make sure thta the user does enter a number, and if they dont, i want to tell them so and ask them to try again.

I have tried this using arrays of characters, and checking each character for its decimal value... but it doesnt seem to work, and my guesses are always somehow made to equal some werid number, normally about 4950, even if i only input 3.

My code for this is here:

int g_input_guess()

{

char guess[4];

int a=0,b=0,c=0,z=0;

cin >> guess;

for(int i = 0;i<4;i++)

{

cout << "guess i is: " << guess; // this outputs some weird stuff... like nothing!! so im not sure, it appears

//that the guess doesnt actually get put in the array or something.

if(guess==113)

{ return -1; }

if(guess>58&&guess<48)

{ cout << "Please enter a real number!\n"; return -2; }

}//end for

a = guess[0]*100;

b = guess[1]*10;

c = guess[2]*1;

z = a+b+c;

return z;

}

any help would be *very* appreciated. Thanks

Link to comment
https://www.neowin.net/forum/topic/475694-c-input-screening/
Share on other sites

8 answers to this question

Recommended Posts

  • 0
  Quote
cin >> guess;

for(int i = 0;i<4;i++)

{

cout << "guess i is: " << guess; // this outputs some weird stuff... like nothing!! so im not sure, it appears

//that the guess doesnt actually get put in the array or something.

nothing is going into the array cause you need to do cin>>guess[some number in here or just 'i' if you're gonna do a for loop]

  • 0

i tried that, both inside and outside the for() loop.

The problem is, i want to be able to check each key pressed by the user, to check if it is actually a number. There is a function, called get() i belive, that works for borland turbo c++... but not the standard c++ code im writing in. My biggest problem is that the cin >> array[] thing only inputs until the return key is pressed, and so i cant check each key *as* they are pressed. If i could find a way to do that, my problem would be solved...

  • 0
  Ianbobisveck said:

int g_input_guess()

{

char guess[4];

int a=0,b=0,c=0,z=0;

cin >> guess;

for(int i = 0;i<4;i++)

{

cout << "guess i is: " << guess; // this outputs some weird stuff... like nothing!! so im not sure, it appears

//that the guess doesnt actually get put in the array or something.

if(guess==113)

{ return -1; }

if(guess>58&&guess<48)

{ cout << "Please enter a real number!\n"; return -2; }

}//end for

a = guess[0]*100;

b = guess[1]*10;

c = guess[2]*1;

z = a+b+c;

return z;

}

any help would be *very* appreciated. Thanks

Okay, I don't know C++, but, i can tell you what is wrong with your code.

first of all, you're cycling through each element of the array, even if the user only enterd a single digit. after using the debugger (you need to know how to use this if you don't) i found that after the input is placed in the array, it is followed by NULL, or 0. so if the user entered just the number 3, your char array would look like this:

guess[0] = '3'

guess[1] = 0

junk in the rest.

so what you need to do is check for a value of 0 and break out of the loop when you find it.

also, this statement in incorrect:

f(guess[i]&gt;58&amp;&amp;guess[i]&lt;48)
{ cout &lt;&lt; "Please enter a real number!\n"; return -2; }
}//end for

it should be >58 or < 48. how can a number be >58 and <48 at the same time?

lastly, your conversion to an integer will only work if they entered 3 characters, and even if they do that it still won't work properly. you are multiplying the ascii value by 100, 10 and 1 instead of the integer value of the input. so what you're doing is '3' * 100 (=5100) instead of 3 * 100 (=300). To convert a character number to an integer subract '0' from it.

If they entered 3 characters your array woudl look like this

guess[0] = '1'

guess[1] = '2'

guess[2] = '3'

guess[3] = 0

So you would be right multiplying guess[0] by 100 and guess[1] by 10, but if they entered in 2 characters:

guess[0] = '1'

guess[1] = '2'

guess[3] = 0

Now it would be incorrect to multiply guess[0] by 100 since they only entered a 2 digit number, so you need to keep track of how many digits were entered.

so heres the code that works, but this doesn't seem like a very good way of doing this, but like I said I don't know C++ so I can't tell you how you should be doing it.

int g_input_guess()
{
	char guess[4];
	int a=0,b=0,c=0,z=0;
	cin &gt;&gt; guess;
	int i; //keeps track of how many chars were entered
	for(i = 0;i&lt;3;i++)
	{
		if (guess[i] == 0) //check for end of user input
		{
			break;
		}

		if(guess[i]==113)//check for 'q'
		{ return -1; 
		}
		else if(guess[i]&gt;58 || guess[i]&lt;48) //check for non-numeric value
		{ 
			cout &lt;&lt; "Please enter a real number!\n"; return -2; 
		}

	}//end for
		//make the conversion depending on how many characters were entered.
		//eg: if only 1 digit was entered, your original method would mutliply it by 100. instead of 1.
	if (i==1) 
	{
		return guess[0] - '0';
	}
	else if (i == 2)
	{
		return (guess[0] - '0') * 10 + (guess[1] - '0');
	}
	else if (i== 3){
		a = (guess[0]-'0')*100;
		b = (guess[1]-'0')*10;
		c = (guess[2]-'0')*1;
		z = a+b+c;
	}



	return z;

You'd also have to worry about what happens if the user decides to type too many characters and overflow the buffer. Hope that helps. Someone with C++ knowledge can tell you if there is a better way to go about it, but thats why it's not working.

  • 0

Also, if you need a you want to be an extremely strict ANSI coder and you need a function to convert integers to ASCII characters, the easiest way is using sprintf():

int n = 2;
char* x;
sprintf(x, "%d", n); /* 'd' specifies a signed integer */

If you are using a std::string instead, here is what it would look like:

std::string x;
int n = 122;
sprintf((char*)x.c_str(), "%d", n);
printf("%s", x.c_str());

Just a tip in case your compiler doesn't have an itoa() or _itoa() function (or you want to be as ANSI standards-compliant as possible). ;)

  • 0

Thanks heaps!!

just a query tho, about this debugger... what would you recomend using/learning? cuz i dont use one, but i have seen one being used (once), and i think it might help me... There is a link to a debugger in your post, but i wasnt sure if that was you or Neowin, and i was wondering what people use, whats good and stuff. Im using linux to compile and run this program, so it'd be good if it worked with that.

Also, what documentation do people use to learn about functions etc? I dont know how to use atoi(), and i dont know where to find out, without just googling it, and there must be a better way then randomly googleing every function i come accross.

Thanks again

  • 0
  Andareed said:

You should not modify the string returned by c_str().

You are right. That's why it is a "dirty" example. I used the language improperly to my advantage. :( Best way when using std::string :

std::string x;
char* buffer = new char();
int n = 122;
sprintf(buffer, "%d", n);
x = buffer;
delete buffer;
printf("%s", x.c_str());

  Ianbobisveck said:

Thanks heaps!!

just a query tho, about this debugger... what would you recomend using/learning? cuz i dont use one, but i have seen one being used (once), and i think it might help me... There is a link to a debugger in your post, but i wasnt sure if that was you or Neowin, and i was wondering what people use, whats good and stuff. Im using linux to compile and run this program, so it'd be good if it worked with that.

Also, what documentation do people use to learn about functions etc? I dont know how to use atoi(), and i dont know where to find out, without just googling it, and there must be a better way then randomly googleing every function i come accross.

Thanks again

Standard C libraries, along with some iostream (well-documented IMHO) - http://www.cplusplus.com/ref/

Pretty much everything including STL - http://www.cppreference.com/

Edited by gohankid77
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Last chance to claim VideoProc Converter AI v7.5 ($78.90 Value) for free by Steven Parker Claim your free license (worth $78.90) today, before the offer expires today, June 18. Equipped with AI tools for video and image enhancement, smoothness, and stabilization. Remaster low-quality videos and photos, convert, edit, compress, download, and record with GPU acceleration! Key Features of VideoProc Converter AI V7.5: AI Video Upscaling: Upscale low-res, old, grainy videos/DVDs/recordings by 400% to HD/4K for stunning visuals on larger screens. AI Image Enhancement: Upscale images and AI art to 8K/10K for better cropping, editing, printing, and sharing. AI Stabilization: Intelligently stabilize shaky GoPro/drone/camera footage with controllable cropping ratios. AI Frame Interpolation: Boost FPS from 30/60 to silky-smooth 120/240/480, or create epic slow-motion effects. 5-in-1 Video Toolkit: Convert, edit, compress, download, and record with the highest possible quality. GPU Acceleration: Expedite video processing, even on older computers. How to get it Please ensure you read the terms and conditions to claim this offer. Complete and verifiable information is required in order to receive this free offer. If you have previously made use of these free offers, you will not need to re-register. While supplies last! Download VideoProc Converter AI V7.5 ($78.90 Value, now FREE) Offered by Digiarty, view other free resources The below offers are also available for free in exchange for your (work) email: Continuous Testing, Quality, Security, and Feedback ($27.99 Value) FREE – Expires 6/18 VideoProc Converter AI v7.5 for FREE (worth $78.90) – Expires 6/18 Macxvideo AI ($39.95 Value) Free for a Limited Time – Expires 6/22 Microsoft 365 Copilot At Work ($60 Value) FREE – Expires 6/25 Natural Language Processing with Python ($39.99 Value) FREE – Expires 6/25 Excel Quick and Easy ($12 Value) FREE – Expires 6/24 The Inclusion Equation: Leveraging Data & AI ($21 Value) FREE – Expires 6/24 The Ultimate Linux Newbie Guide – Featured Free content Python Notes for Professionals – Featured Free content Learn Linux in 5 Days – Featured Free content Quick Reference Guide for Cybersecurity – Featured Free content We post these because we earn commission on each lead so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin The above deal not doing it for you, but still want to help? Check out the links below. Check out our partner software in the Neowin Store Buy a T-shirt at Neowin's Threadsquad Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: An account at Neowin Deals is required to participate in any deals powered by our affiliate, StackCommerce. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through the branded deals site.
    • They pulled this same crap with Google Workspace. "hey you get AI now so we are raising your prices". I disabled it for my org but we still have to pay. F this stupid 1984 tiny hat spy crap.
    • Samsung could unveil its Galaxy XR headset ‘Project Moohan' in September by Sagar Naresh Bhavsar Next month, Samsung is expected to unveil the Galaxy Z Fold7, the Galaxy Z Flip7, and an affordable Galaxy Z Flip7 FE, along with the Galaxy Watch8 series. However, the launches don't end there. A fresh report out of South Korea hints that Samsung could launch its much-awaited Galaxy XR augmented reality headset in September. The company has codenamed its first XR headset as "Project Moohan," which translates to "Project Infinite." Samsung has already showcased the Galaxy XR headset a few times in the past. In fact, popular tech YouTuber Marques Brownlee - also known as MKBHD -, got his hands on the Galaxy XR and revealed interesting details about the upcoming device. The Galaxy XR is rumored to come with a sharper display compared to the Apple Vision Pro and run on Google's new operating system for AR and VR headsets, the Android XR. Fast forward to now, Korean publication Newspim reports that Samsung is ready to launch the Galaxy XR headset on September 29 in its home country. Notably, the headset will be unveiled at an Unpacked event and later will go on sale on October 13. Globally, the Galaxy XR headset is expected to launch soon afterwards, though any specific date isn't mentioned. Additionally, the report suggests that fans can expect more teaser videos and prototypes of the headset at the upcoming Unpacked event for the Galaxy Z Fold7 and Flip7. The report also spills some details about the specifications of the Galaxy XR headset. Under the hood, it could run on Qualcomm's new XR2+ Gen 2 chip, made using Samsung's 4nm process. Samsung is also expected to introduce tight integration with its Galaxy ecosystem to offer a connected experience. It will be interesting to see how Samsung holds up against the likes of Meta, which already dominates the XR market, while Apple struggles with high Vision Pro prices.
    • I've put it behind a login for the time being.  I had something like 600,000 requests from just from Alibaba IP addresses that didn't clarify they were bots or scrapers, and so not easy to block using user agent filtering.  I didn't have any issues with bandwidth or accessibility, but that's 600,000 requests just from one cloud provider made to my spinning rust hard drives, that I have to personally pay for when they die, by bots being ran by corrupt mega corporations ignoring my polite requests that they not scrape me and that the information only be accessed by real humans. If any of y'all here were actually using my Kiwix mirror, I have no issue whatsoever creating a username and password for you, just hit me up using one of the methods listed on my personal site and I'll make one for you. https://marcusadams.me
  • Recent Achievements

    • Week One Done
      vivetool earned a badge
      Week One Done
    • Reacting Well
      pnajbar earned a badge
      Reacting Well
    • Week One Done
      TBithoney earned a badge
      Week One Done
    • First Post
      xuxlix earned a badge
      First Post
    • First Post
      Tomek Święcicki earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      672
    2. 2
      ATLien_0
      287
    3. 3
      Michael Scrip
      223
    4. 4
      +FloatingFatMan
      195
    5. 5
      Steven P.
      143
  • Tell a friend

    Love Neowin? Tell a friend!