3

I'm trying to back-up in my programming and learn something that I somehow missed (unless I'm not understanding the problem). I am trying to prompt the user to enter the name of a project, and I want to store that name in a variable. Normally I would use getline() or std::cin >> std::string some_string but the assignment is asking me to do this, without the use of strings. "You can NOT use the string class - instead use array's of characters." Therein lies the question: How do I take the user input and store them in an array of chars?

The user is going to enter a word and then hit enter... How do i capture that into an array of chars? If the word was coming in one char at a time I could just add it to the array, dynamically expanding if needed, but when it comes in a block of char's like that I am lost for ideas. Thanks!

2 Answers 2

5

The member function cin.getline() allows you to specify a character buffer and length.

char name[32];
cin.getline(name, 32);

Though any C++ assignment that would ask you specifically to use character arrays instead of strings (especially in this context), is suspect.

Sign up to request clarification or add additional context in comments.

5 Comments

cin.getline(name, sizeof(name));
@karl: Dangerous, because if name is changed to a pointer, it still compiles but does the wrong thing.
Of course, but this suggestion goes hand in hand with what is stated in the answer. If @Chad had used pointers, I would not have left my previous comment. :)
And that is why I say if an assignment is forcing you to use character arrays for this it is suspect. My guess is an old-fashioned "C with classes!" approach.
@karl: But it's fairly straightforward to use one of the countof implementations instead, which is completely safe. If you're going to replace the hard-coded constant with a computation, you might as well use the right computation.
0

Try this:

char arr[100];
cin >> arr;

7 Comments

Terrible idea. No way to guarantee the buffer won't overflow. This kind of thing leads to bugs down the road.
Note: You must never do this after you finish this programming course. You have created a buffer overflow, which is the root cause of various security bugs.
Call cin.width(100); beforehand.
@Amardeep: No way to guarantee it? Sure you can, just define template <size_t N> istream& operator>>(istream&, char (&)[N]) and check the length N therein.
@Ben Voigt: That's plenty clever but does adding obscurity make a poor solution better than an intrinsically safer solution like Chad's?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.