Sign in to follow this  

weird C++ thingy

This topic is 4840 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok guys, i need a code that will make the user input something and input it until the user either enters a letter or a negative number. And it must be able to handle values like 100000 and such. so how do i do this? this is what i have:
#include <iostream>
#include <cctype>

using namespace std; //I know it's nooby, but i dont care atm.

int main(void)
{
    char temp;
    int value;
    cout << "Write a value: ";
    cin >> temp;

    while (isdigit(temp) && temp >= 0)
    {
        value = temp;
        cout << "The value is " << value;
        cout << "Write a new value: ";
        cin >> temp;
    }

    cout << "Press any key to continue.";
    cin.get();
    cin.get();
    return 0;
}


edit : oops i forgot to say some things, but the thing is that char can't handle big amounts, i think CHAR_MAX on my comp is 127 or something, and int can't handle letters. So how do i fix this? Should i use some sort of array or something? :s

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Look at the gets functions. (gets, fgets, ...)
and use a buffer : char buffer[128] for exemple.
atoi is a function to convert a string to an integer.

hope that helps.

neyna

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
dont forget : #include


#include

int main() {
char buffer[128];
while( strcmp(gets(buffer),"quit")!=0 ) {
printf("You wrote : %s\n",buffer);
}
return 0;
}


neyna

Share this post


Link to post
Share on other sites
off the top of my head, might not be syntaticaly correct but
i hope you get the idea, if not, query me back.


#include <cstdio>
#include <iostream>

using namespace std;

bool isNumber(const char *str)
{
// may need to trim str for leading/trailing whitespace

int start = 0;
if( str[0] == '-' ) // handle negatives too
start++;

for(int i=start; i<strlen(str); i++)
if( !isdigit(str[i]) )
return false;
return true;
}

int main()
{
bool done = false;

char temp[40] = {0}; // 40 chars should be enough
int ival = 0;

while( !done )
{
cout << "The value is " << temp;
cout << "Write a new value: ";
cin >> temp;

bool isNum = isNumber(temp);

if( isNum )
ival = atoi(temp);

if( isNum && ival < 0 || !isNum ) // if its negative OR a string
done = true;
}


}





PS. i hope that wasnt a homework assignment, because if it was
your cheating nobody but yourself.

Share this post


Link to post
Share on other sites
Quote:
Original post by Tobbe
I dont really understand, how would the code be?



#include <stdio.h>

int main() {
char buffer[128];
int number=0;
while( strcmp(gets(buffer),"quit")!=0 ) {
printf("You wrote : %s\n",buffer);
number=atoi(buffer);
// ..........
}
return 0;
}




hope that helps.

neyna

Share this post


Link to post
Share on other sites
ok thank you all. I just thought that it might be an easier or obvious way to do it. But i will try to construct a longer function instead.
And it's not homework because i dont have programming in school :(

Btw, what's the difference between this:

char blabla = 5;
int blablabla = atoi(blabla);


and this:

char blabla = 5;
int blablabla = (int) blabla;

Share this post


Link to post
Share on other sites
quick explination of my code example


while done is false

get user input
test if it is numberic

if( numeric )
convert to integer value

if( numeric and less than zero OR is not numeric )
set done = true
loop

Share this post


Link to post
Share on other sites
atoi takes a const char* argument, and does a char by char
conversion (so its guaranteed to be numeric)

casting from a char to an int works but only if the char
is a digit (between '0' and '9') this is because ASCII digits
map directly to their values BUT letters etc. do not.

eg. try this

char a = '3';
int val = (int) a;

cout << val << endl;
------------------------------
char a = 'z';
int val = (int) a;

cout << val << endl;

Share this post


Link to post
Share on other sites
Quote:
Original post by Tobbe

Btw, what's the difference between this:

char blabla = 5;
int blablabla = atoi(blabla);

---

char blabla = 5;
int blablabla = (int) blabla;




The first method is the right way because atoi reads the buffer and look for an integer :
buffer = [1,2,3,4,5,\0,..........] for exemple
and then int blabla = 1*10^4+2*10^3+...5*10^0

if you cast it, u will have a very weird result because the byte will be read as an integer and not a string !!!

for exemple : [1,2,\0, .... ] => 0x01 0x02 .... in hexa
and if u cast it the integer will be 0x0102 , wich is not 12 but 1*16^2 + 2 = 258.

Unnderstood ?

i advise you to read a book about C/C++ programming and read carefully the representation of data in memory. Otherwise u will have a lot of problems ans you never will understand the pointers.

Hope that helps.

neyna

--- EDIT
i made things easy to understood, but '1' and '2' as char as not coded 0x01 and 0x02 in ASCII, but 0x01 + 0x30 (48 in decimal is ASCII code for 0 if my memory is good)

[Edited by - Neyna on September 14, 2004 4:12:19 AM]

Share this post


Link to post
Share on other sites
yeah i have a book, but it's never talking about C, only C++ and I'm very new to programming so it's a bit hard. well anyway thanks all. :D
edit: and i understood btw, thanks :-D

Share this post


Link to post
Share on other sites
I understand it's hard.
And c/c++ is not easy to begin because it's really near machine. I mean u play directly with memory. And functions are low-level.

Try a more easier langage to start, like php (C-like but no memory allocation ...) or Visual basic (i hate it, but easy to learn) or even delphi (i hate it too).

(i hate them because they are too simple i think, and only for windows)

One advise, read tutorial on the web or buy a good book.

Neyna

Share this post


Link to post
Share on other sites
Quote:
Original post by silvermace
casting from a char to an int works but only if the char
is a digit (between '0' and '9') this is because ASCII digits
map directly to their values BUT letters etc. do not.


Erm...

Casting a char to int will work with any char, it will simply set the int to the same value. ASCII digits do not map directly to their values (0 = 48 in ASCII).

char blabla = 5;
int blablabla = (int) blabla;

int blablabla will be set to the value 5.

char blabla = '5';
int blablabla = (int)blabla;

int blablabla will be set to the value 53 (Ascii '5').

Share this post


Link to post
Share on other sites
My book is very good, but it never says anything about C.
I decided to start with C++ because it is powerful, and i think that it might be weird to go from like basic to C++. Like i discover that I use if then else instead of if else. or use = at comparisons instead of ==. and like that. So i will learn C++ first, and i will try to rtfm before asking stupid questions again ;) anyway thanks.
btw, i have a few friends who know C++ so thats another reason :)

Share this post


Link to post
Share on other sites
Quote:
Original post by Tobbe
Like i discover that I use if then else instead of if else. or use = at comparisons instead of ==. and like that.


if (..) {..} else {..} is commune to C/C++

In a if statement the operator for comparaison is == !!
= is always the affectation.

But u can do : if( a=10 ) {}
it will be always true !! because it is equivalent to :
if( (a=10) != 0 ) {} <=> if( a != 0 ) {} <=> if( 10 != 0 ) {}

Theres no boolean in C/C++, 0 is false, the rest is true.

neyna

Share this post


Link to post
Share on other sites
Yes I know that, i just meant that if i learn basic i would do that by default. I'm not a complete n00b only 99% :p
edit: why is C++ more powerful than C? Is it because it's object oriented?

[Edited by - Tobbe on September 14, 2004 5:22:35 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Tobbe
Yes I know that, i just meant that if i learn basic i would do that by default. I'm not a complete n00b only 99% :p


ah ok, didn't caught that.

Quote:
Original post by Tobbe
edit: why is C++ more powerful than C? Is it because it's object oriented?


exactly ! that was the main progress.

C++ has some more feature by the way : exception handling, new libs (vectors, stacks ....) ...

neyna

Share this post


Link to post
Share on other sites
Lol. I just found out i used a single = at a comparison. because i'm not used to while loops :P
and Btw, i solved that problem now, but im too lazy to translate the code to english and post it now i might later. :-p

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
Quote:
Original post by Tobbe
Yes I know that, i just meant that if i learn basic i would do that by default. I'm not a complete n00b only 99% :p


ah ok, didn't caught that.

Quote:
Original post by Tobbe
edit: why is C++ more powerful than C? Is it because it's object oriented?


exactly ! that was the main progress.

C++ has some more feature by the way : exception handling, new libs (vectors, stacks ....) ...

neyna
I'd say templates is one of the most important, don't forget them :)

Share this post


Link to post
Share on other sites
C++ offers many new things not found in C. It is effectively a different language which just *happens* to be compatible enough in syntax to let you embed C-looking stuff in your C++. Of course, it so happens *by design*, but you're probably better off not thinking of C++ in that way.

Now then. Something like this perhaps?


int value;

while (true) {
cin >> value;
if (cin.fail() || value < 0) { break; }
do_stuff_with(value);
}
// if the input is non-numeric, then the cin stream will 'fail'.
// Otherwise we read an integer into 'value'; at that point we
// are able to test it for positive-ness.

Share this post


Link to post
Share on other sites

This topic is 4840 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this