• Advertisement
Sign in to follow this  

Variable/Char/ w/e help..

This topic is 3627 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

!!Newbie Alert!! Hey, I've got an extremely simple code where the system prompts you for your name and you enter it and it says, "Hello, "name". But It only says the first letter of the name :\ Heres my code:
#include "stdafx.h"

#include <iostream>

using namespace std;

int main()

{
	char name;

	cout << "Please enter your name. \n";
	cin >> name;
	cout << "Hello.." << name << "\n";

system("PAUSE");

}

Share this post


Link to post
Share on other sites
Advertisement
char stores a character (i.e. a single letter, punctuation mark, digit or one of a few other things). You want to store a sequence of characters – this sequence is called a string and is represented using the std::string type, rather than char.

Where you have char name, you want string name. To use std::string, you must put #include <string> at the top of your code (next to where you've got #include <iostream>).

(Incidentally, I'm calling it both string and std::string above – std::string is its fully qualified name, but you've got using namespace std; at the top of your code, which means that the compiler knows you mean std::string when you say string; this std:: bit can be used to differentiate between different types with the same name – the standard library has std::string to represent text, but you might have a string type of your own that refers to the piece of twine, and the compiler can't tell them apart unless you use their fully-qualified names)

Share this post


Link to post
Share on other sites
Thanks! Works great! :D

Question 2: I have changed the code so it is now a survey and I want it so if they put in one response, the system sends one message, but when the input the second, it feeds out a different message, is this possible?

Share this post


Link to post
Share on other sites

if(gender == "male")
{
cout << "Disappointing." << endl;
}
else if(gender == "female")
{
cout << "How you doin'? ;)" << endl;
}
else
{
cout << "Bit of both, eh?" << endl;
}


Something like that?

If that is what you're looking for, be aware that it's case sensitive.

Really, you should get into the habit of using buffers instead of the "string" type. e.g:

char name[32];


When working with those, though, you need to watch out for the potential for buffer overflows... but that may be too much to worry about if you're just starting.

Share this post


Link to post
Share on other sites
Quote:
Original post by gemin ta
Really, you should get into the habit of using buffers instead of the "string" type. e.g:

char name[32];


When working with those, though, you need to watch out for the potential for buffer overflows... but that may be too much to worry about if you're just starting.


Why would you *voluntarily choose* to use raw char arrays over std::string?

Share this post


Link to post
Share on other sites
Quote:
Original post by gemin ta
Really, you should get into the habit of using buffers instead of the "string" type. e.g:

char name[32];


When working with those, though, you need to watch out for the potential for buffer overflows... but that may be too much to worry about if you're just starting.


What!?!? Why on earth would you suggest something like that? Using character arrays as strings is an unfortunate throwback to C that should NEVER be used in C++. They are less intuitive, prone to security errors, and lead into the whole arrays/pointers syntax nonsense.

To the OP: Stick with std::string. It's a core part of the C++ language and using it correctly will save you hours of debugging and frustration.

Share this post


Link to post
Share on other sites
Quote:
Really, you should get into the habit of using buffers instead of the "string" type. e.g:

char name[32];
Why do you say that? (Just curious...)

Share this post


Link to post
Share on other sites
Using char arrays to start makes sense from a pedagogical point of view. It reminds you that C++ is first and foremost a highly developed low level language (where you have to manage your memory manually, and watch out for buffer overflows). Attempting to use/teach C++ like a "true" high level language (HLL), like Python for example, you fail to recognize its true nature.

Share this post


Link to post
Share on other sites
Hit a nerve with that one. ;) Ouch!

I suppose I've just been conditioned by years of ASM programming to use the closest to the 'base level'. There're no real problems with going "raw" if you... I dunno... know what you're doing? Why put up with the overheads otherwise?

I guess (as with many things) the choice depends on your needs and capabilities. I'm just one of those people who likes to promote taking the extra time to handle something on a more "personal" level... even at the cost of time or the expense of possible risk. To put it quite bluntly, I think that while using shortcuts when programming may be efficient if development time is in question, they can also promote laziness and give people warped ideas of how things actually work. I've met many C++ programmers who are heavily into OOP, etc. who actually believe that they're writing 'C++ scripts' for the processor to read and parse.

I can sense a debate already here (usually fuelled by people who argue for the sake of it and/or want to compare the size of their you-know-what) so... I won't be replying again. ;P I've got my point across.

Share this post


Link to post
Share on other sites
Quote:
I suppose I've just been conditioned by years of ASM programming to use the closest to the 'base level'. There're no real problems with going "raw" if you... I dunno... know what you're doing? Why put up with the overheads otherwise?


No, there's no problems if you know "why" you're doing it.

Quote:
Attempting to use/teach C++ like a "true" high level language (HLL), like Python for example, you fail to recognize its true nature


Depends. Perhaps it's your perspective that C++ *must* be low-level. But it really doesn't need to be.

Unfortunately, majority of materials available is C with classes, the rest is C++ with C.

But unless the course is taught as part of CS curriculum, there's no reason whatsoever to even mention any C concepts. Standard library provides decent utility (incredibly minimal compared to other languages), but for teaching algorithms and data structures, the basic application concepts (non-GUI), console IO, and various utility programming, there's is exactly zero need to even mention any kind of C legacy.

If the course is intended for industry application (beyond beginner level), then legacy will creep up due to libraries, not C++ itself.

This is easily tested. Implement any algorithm purely with C++ idioms and classes. If you add some form of smart pointers, you can almost copy-paste Java or C# code.

To teach programming, C doesn't need to be mentioned. To teach C++, it needs to be.

Again: "why" is more important than "how". Why is someone learning C++. And as always, one must learn to crawl before one can walk. Pure C++ is hence a better choice, than C/C++ mess.

Share this post


Link to post
Share on other sites
I realize you've said you're not going to argue the point further, but I'm going to go ahead and reply, just to make sure the OP is exposed to multiple points of view.
Quote:
There're no real problems with going "raw" if you... I dunno... know what you're doing? Why put up with the overheads otherwise?
Even if you know what you're doing, the probability of error is almost certainly going to be higher when manual manipulation of pointers, buffers, and so forth is involved. Furthermore, it is not a given that doing it the 'right way' will incur additional (noticeable) overhead.
Quote:
I'm just one of those people who likes to promote taking the extra time to handle something on a more "personal" level... even at the cost of time or the expense of possible risk.
Sounds like false economy to me. You lose valuable development time, increase the chances of errors/bugs cropping up in your code, and for what gain? A little extra performance, maybe? (And even that isn't a certainty - depending on what you're doing, the 'C++ way' of doing something can be as fast or faster than the 'C way'.)
Quote:
To put it quite bluntly, I think that while using shortcuts when programming may be efficient if development time is in question, they can also promote laziness and give people warped ideas of how things actually work.
Agreed. I don't think we're quite to the point yet where programmers don't need to know what's going on under the hood (this is even true with higher level languages such as C#), and I think programmers who have had to spend some time mucking about in assembly and C sometimes have a better understanding of how to effectively use the tools available to them in a mid-level language such as C++.

But to actually use a character array rather than std::string in production code? I don't think that 'handling things on a more personal level' quite cuts it in terms of justifying such a decision.

I think part of the reason your post got such a strong reaction was that you made a simple, absolute statement - 'you should get in the habit of using buffers rather than string' - without offering any further explanation or justification. In this forum especially, if you're going to make a suggestion that goes directly against what most C++ developers would consider to be 'best practice', some supporting arguments are probably going to be in order.

Share this post


Link to post
Share on other sites
I dont even make suggestions one way or the other anymore on this board about these matters.
I once responded to a post where the original poster seemed pretty fluent in c plus plus but wanted a better understanding of how bytes/structs/data types aligned and worked in an array he was working with, and why he wasnt getting the result he expected. The post after mine, or before I could post my reply turned into the benefits of the STL, why he wasnt using a vector, and the reason why he had char* in his code at all. Despite the fact that it didnt seem like anything more then an experiment on how the language handles things.
My point being, a lot of the time on this board the problem in question doesnt even resemble production code, or the time constraints associated with, yet people swoop in advocating the 'better' or more 'accepted' why of solving a problem, and the whole thing goes off track.
The original poster here seems to be getting a feel for how things work, and probably would benefit from not dealing with buffer overflow problems and memory management right now. Yet, even if he learned how to do it using char buffer in this thread, I doubt very much this would be the last chance to introduce him to the std::string.
Myself I think the first responder pretty much had it handled, but unfortunately all that pointer/array syntax nonsense is a part of that big C that comes before the plus plus and should probably be understood, if only because someone might ask you how it works one day and even newer languages like C# dont completely insulate you from it.

Share this post


Link to post
Share on other sites
Quote:
Original post by Antheus
Quote:
I suppose I've just been conditioned by years of ASM programming to use the closest to the 'base level'. There're no real problems with going "raw" if you... I dunno... know what you're doing? Why put up with the overheads otherwise?


No, there's no problems if you know "why" you're doing it.

Quote:
Attempting to use/teach C++ like a "true" high level language (HLL), like Python for example, you fail to recognize its true nature


Depends. Perhaps it's your perspective that C++ *must* be low-level. But it really doesn't need to be.

Unfortunately, majority of materials available is C with classes, the rest is C++ with C.

But unless the course is taught as part of CS curriculum, there's no reason whatsoever to even mention any C concepts. Standard library provides decent utility (incredibly minimal compared to other languages), but for teaching algorithms and data structures, the basic application concepts (non-GUI), console IO, and various utility programming, there's is exactly zero need to even mention any kind of C legacy.

If the course is intended for industry application (beyond beginner level), then legacy will creep up due to libraries, not C++ itself.

This is easily tested. Implement any algorithm purely with C++ idioms and classes. If you add some form of smart pointers, you can almost copy-paste Java or C# code.

To teach programming, C doesn't need to be mentioned. To teach C++, it needs to be.

Again: "why" is more important than "how". Why is someone learning C++. And as always, one must learn to crawl before one can walk. Pure C++ is hence a better choice, than C/C++ mess.


That's why C++ shouldn't be taught to a beginner, because other languages are much more suitable to learn algorithms (Scheme or Haskell for example).

Still, if you have to, or want it, why not learn it like it was "part of a CS curriculum", that is, with an understanding of how the language and the machine really works? I think this is exactly what you say, crawling before you walk.

Share this post


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

That's why C++ shouldn't be taught to a beginner, because other languages are much more suitable to learn algorithms (Scheme or Haskell for example).


That wasn't questioned. But when you're faced with someone who did start with C++, take the lemons and make lemonade. Why burden them with learning concepts of two languages, when, for the given task and purpose, one is provably enough.

Memory management is indeed part of C++. But it can be classified as advanced topic, without impeding learning process (programming, not C++), which is higher priority.

Quote:
Still, if you have to, or want it, why not learn it like it was "part of a CS curriculum", that is, with an understanding of how the language and the machine really works? I think this is exactly what you say, crawling before you walk.


Because someone without being in actual CS course, without having strict supervised guidance at every step, without following peer reviews materials, working on their own, without any programming experience at all will simply find that to be an impossible task.

Share this post


Link to post
Share on other sites
Quote:
Original post by gemin ta

if(gender == "male")
{
cout << "Disappointing." << endl;
}
else if(gender == "female")
{
cout << "How you doin'? ;)" << endl;
}
else
{
cout << "Bit of both, eh?" << endl;
}


Something like that?

If that is what you're looking for, be aware that it's case sensitive.

Really, you should get into the habit of using buffers instead of the "string" type. e.g:

char name[32];


When working with those, though, you need to watch out for the potential for buffer overflows... but that may be too much to worry about if you're just starting.



Ok.. well How would I exactly implement this into my code because I'm not exactly sure. Heres what I did which is almost certainly wrong..

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main()

{
string name;
string age;
string pets;
double dpetsnumber;
char Prompt;
string petscorrect;

cout << "Please enter your name. \n";
cin >> name;
cout << "Hello.." << name << "\n";
cout << "How old are you? (Spell out the number) \n";
cin >> age;
cout << "So your name is " << name << " and you're " << age << " years old, interesting. \n";
cout << "Do you have any pets? \n";
cin >> pets;
cout << "So you do have pets, how many? \n";
cin >> dpetsnumber;
cout << "So you have " << dpetsnumber << " pet(s), correct? (y/n) \n";
if(petscorrect == "yes")
{
cout << "Cool." << endl;
}
else if(petscorrect == "no")
{
cout << "That's cool ;)" << endl;
}
else
{
cout << "Bit of both, eh?" << endl;

}


system("PAUSE");

}




EDIT::::: SORRY! fixed it! Added a cin >> petscorrect; before it.. thanks again!

Share this post


Link to post
Share on other sites
Gaaaaaah, yet another question ! (I know when am I gonna shutup.. <_<) Anyways, I'm trying to make it so in the question: Do you have any pets? if they answer no it exits instead of continuing. How would I do this?

Share this post


Link to post
Share on other sites
Ok, one thing that is important when coding is consistency. For example, keeping all variables lowercase (I'm looking at you, "Prompt" [smile]). Also, the number of pets should probably be an integer. I'm not sure whether handling the case of having 3.4 pets is reasonable [grin]. Then, you need to handle if the user has no pets. One way of doing this is skipping asking them whether they have pets or not and asking them how many pets they have. If they don't have any pets then the user would enter 0.

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Please enter your name. \n";
string name;
cin >> name;

cout << "Hello.." << name << "\n";
cout << "How old are you? (Spell out the number) \n";
string age;
cin >> age;

cout << "So your name is " << name << " and you're " << age << " years old, interesting. \n";
cout << "How many pets do you have?\n";
int petCount;
cin >> petCount;

if( petCount > 0 )
{
// handle the user talking about pets
}
else
{
// handle the user doesn't have pets
// to exit from main, use "return"
// conventionally, return 0 to indicate "success"
// return non-zero to indicate failure
// failure is usually only important
// to programs called from other programs
// the calling program can examine the value and decide to do something
// however, not having pets isn't really an error, so we return success
return 0;
}
}



Another trick is to only declare variables when you are going to use them. This helps stop errors such as using the wrong variable in the wrong place.

Share this post


Link to post
Share on other sites
Great! Works perfectly! But how would I make it so instead of exiting, it just continues the survey in a different way? For example if you answer that you have pets, it asks you more questions about pets, however if you answer that you have 0 pets, it continues on with the rest of the survey. Would you be kind enough to give an example of that code? Thanks. :)

[Edited by - sssummer on March 16, 2008 5:36:47 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by gemin ta
Hit a nerve with that one. ;) Ouch!

I suppose I've just been conditioned by years of ASM programming to use the closest to the 'base level'. There're no real problems with going "raw" if you... I dunno... know what you're doing? Why put up with the overheads otherwise?


You've already mentioned one of the problems already: Buffer overflows, which last I checked was still one of the leading causes of security holes. How is that not a very real problem? (This is rhetorical, I saw you don't intend to reply, that's fine. Point of interest: My full name is already a mere 5 characters away from overflowing your example buffer. Were I to get one of those fancy hyphenated last names if/when I'm married, you'd certainly have a problem.)

For the 99% of programs where text processing is nowhere near your bottlenecks, it's not worth the extra writing, debugging, and maintenance time to use raw character buffers throughout your program -- to think otherwise is pure audacity.

For the remaining 1%, a far better solution would be to wrap up access into a fixed_string type to centralize the code and testing, allowing you to maintain a nice set of invariants about what will happen when shit hits the fan, allowing you to simplify the rest of your code.

So, in conclusion:

Quote:
Really, you should get into the habit of using buffers

I completely and absolutely disagree. You should stay in the habit of using things that wrap buffers safely. You should get into the habit of writing those wrappers if needed as well!

Share this post


Link to post
Share on other sites
Quote:
Original post by sssummer
Great! Works perfectly! But how would I make it so instead of exiting, it just continues the survey in a different way? For example if you answer that you have pets, it asks you more questions about pets, however if you answer that you have 0 pets, it continues on with the rest of the survey. Would you be kind enough to give an example of that code? Thanks. :)


You can basically just lop off the else statement.

#include <iostream>
#include <string>

using namespace std;

int main()
{
cout << "Please enter your name. \n";
string name;
cin >> name;

...

if( petCount > 0 )
{
cout << "Please enter your favorite pet's name. \n";
string pet_name;
cin >> pet_name;

...
}

...

cout << "Did you like this quiz? \n";
string liked_quiz_answer;
cin >> liked_quiz_answer;
}


Share this post


Link to post
Share on other sites
Ok FINAL question. (For this topic :D) I have finished that survey project and I'm now making a text based commander style RPG where your strategic choices determine whether or not you lose. Sounds hard <_<. How do I make it so instead of choosing a response based on a number like I did with the pets problem it gives you the option of a, b, or c and gives an output from there?

Share this post


Link to post
Share on other sites
Quote:
Original post by sssummer
Ok FINAL question. (For this topic :D) I have finished that survey project and I'm now making a text based commander style RPG where your strategic choices determine whether or not you lose. Sounds hard <_<. How do I make it so instead of choosing a response based on a number like I did with the pets problem it gives you the option of a, b, or c and gives an output from there?


This is starting to sound a bit like homework...

To the computer, a char-acter (a, b, c, and etc) is a number. A difference is that a char is displayed as a letter. For example the character 'a' is represented as 97 (on the ascii chart). Therefore you could say if ( charInput == 97 ) to check if charInput is an 'a', but how can you remember that 97 is 'a'? Instead, you can if ( charInput == 'a' ) to check if charInput is the same as 'a' (is the same as 97).

If you give a char to std::cin it will expect to read a single character. An important note: '5' != 5, but ('5' - '0') = 5

If you give a int to std::cin it will cause grief if you give it anything but a number.


Sorry if this doesn't make any sense... I tried :)

Share this post


Link to post
Share on other sites
Quote:
Original post by _fastcall
Quote:
Original post by sssummer
Ok FINAL question. (For this topic :D) I have finished that survey project and I'm now making a text based commander style RPG where your strategic choices determine whether or not you lose. Sounds hard <_<. How do I make it so instead of choosing a response based on a number like I did with the pets problem it gives you the option of a, b, or c and gives an output from there?


This is starting to sound a bit like homework...

To the computer, a char-acter (a, b, c, and etc) is a number. A difference is that a char is displayed as a letter. For example the character 'a' is represented as 97 (on the ascii chart). Therefore you could say if ( charInput == 97 ) to check if charInput is an 'a', but how can you remember that 97 is 'a'? Instead, you can if ( charInput == 'a' ) to check if charInput is the same as 'a' (is the same as 97).

If you give a char to std::cin it will expect to read a single character. An important note: '5' != 5, but ('5' - '0') = 5

If you give a int to std::cin it will cause grief if you give it anything but a number.


Sorry if this doesn't make any sense... I tried :)





LOL WUT. >_> I didn't understand a work you said lol.

Share this post


Link to post
Share on other sites

char chInput;

std::cout << "Enter 'a', 'b', or 'c'" << std::endl;
std::cin >> chInput;

if ( ch == 'a' )
; // Do stuff




-- is basically all I said.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement