We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

stringstream & getline() - How can it get a char pointer? C/C++

F-J-K
F-J-K asked
on
Medium Priority
3,374 Views
Last Modified: 2012-05-06
Ok experts, i'm stuck with this:

1. The code between *** 1 ***, works fine, but input.c_str() only converts to const char*,
i'm just curious! Is there a way i can make it convert to char*?

2. In *** 2 *** code, i get this: error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'const char *' (or there is no acceptable conversion). How can i handle this situation with stringstream()?

3. Assume i have this variable "char userInput[MAX_DATA];", what is the best what put data into it? Is it through cin>>, or ? - I think getline() - stringstream is a good one. Thus, i want to know how to do this on getline - stringstream unless if there is a better way to handle it.

4. Referring to *** 2 ****. Assume user inserted a number, so clientInput carries number. However, i need to ensure that user entered digits & not any other data. Is there any ready function in the C++ standard library that does the job?

5. Referring to *** 2 ****. If clientInput meant to carry an IP address & user lets say entered 121.33.200.22 - Is there a ready function that can check that user entered an IP address? so i can pass the variable to a function safely. I'm trying to avoid race conditions.

6. The two piece of codes below seems very similar. Sometimes i feel in the second code, i'm just adding an extra code after getline(). Sometimes i think it is more efficient to have the stringstream. The second one seems more robust, but in the first one i'm doing this input.c_str() which is not a significance difference, so is the second one is better in terms of security & filtering? Why?

7. Assume user inserted an IP address into clientInput. When i want to validate it, the algorithm of validation briefly will be as following:
a. convert the stream of chars into string
b. count the 4 dots
c. make sure other inputs are digits (excluding dot).
Do you have any suggestions?

I apologize for my long boring questions. Just answer what you know, one question or whatever you can share.

Best regards,
F.J.



//********* 1 **********//
const char *clientInput;
string input;
getline(cin, input);
clientInput = input.c_str();
//******** 1 **********//
 
//******** 2 **********//
const char *clientInput;
string input;
getline(cin, input);
stringstream ss(input);
ss >> clientInput;
//******** 2 **********//

Open in new window

Comment
Watch Question

Top Expert 2007

Commented:
>>1. The code between *** 1 ***, works fine, but input.c_str() only converts to const char*,
>>i'm just curious! Is there a way i can make it convert to char*?
   char* abc = const_cast<char *>(input.c_str());

>>2. In *** 2 *** code, i get this: error C2679: binary '>>' : no operator found which takes a right-hand operand of >> type 'const char *' (or there is no acceptable conversion). How can i handle this situation with stringstream()?
The problem is that
   const char *clientInput;
is const and so can't be modified.
CERTIFIED EXPERT
Top Expert 2009
Commented:
>> 1. The code between *** 1 ***, works fine, but input.c_str() only converts to const char*,
>> i'm just curious! Is there a way i can make it convert to char*?

Do you need to be able to write to the string ? If not, there's no need to have a char*. A const char* is sufficient.
Alternatively, you can use this getline that reads into a char* :

        http://www.cplusplus.com/reference/iostream/istream/getline.html

for example :

        char clientInput[1024] = "";
        cin.getline(clientInput, 1024);


>> 2. In *** 2 *** code, i get this: error C2679: binary '>>' : no operator found which takes a right-hand operand
>> of type 'const char *' (or there is no acceptable conversion). How can i handle this situation with stringstream()?

You cannot write to the string using a const char*. const char* is a pointer to const char.


>> 3. Assume i have this variable "char userInput[MAX_DATA];", what is the best what put data into it? Is it
>> through cin>>, or ? - I think getline() - stringstream is a good one. Thus, i want to know how to do this on
>> getline - stringstream unless if there is a better way to handle it.

Depends what kind of data you need. If you absolutely need a char*, you can use the getline I mentioned in 1). Otherwise, I'd stick with an std::string.


>> 4. Referring to *** 2 ****. Assume user inserted a number, so clientInput carries number. However, i need to
>> ensure that user entered digits & not any other data. Is there any ready function in the C++ standard library
>> that does the job?

If you convert the string to an integer, then the invalid characters will be ignored. For example :

        std::string clientInput;
        getline(cin, clientInput);
        std::stringstream ss(clientInput);
        int value = 0;
        ss >> value;


>> 5. Referring to *** 2 ****. If clientInput meant to carry an IP address & user lets say entered 121.33.200.22 -
>> Is there a ready function that can check that user entered an IP address? so i can pass the variable to a
>> function safely. I'm trying to avoid race conditions.

I'm not sure what race conditions have to do with this, but standard C++ does not have a function for reading an IP address from string.
Many implementations have the inet_pton function that does this :

        http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#inet_ntopman


>> 6. The two piece of codes below seems very similar. Sometimes i feel in the second code, i'm just adding an
>> extra code after getline(). Sometimes i think it is more efficient to have the stringstream. The second one seems
>> more robust, but in the first one i'm doing this input.c_str() which is not a significance difference, so is the
>> second one is better is terms of security? Why?

Security has nothing to do with this.
The way you extract data from a string is up to you. stringstreams are handy for extracting non-string data from a string, or for extracting multiple data elements. If you simply need the string, then there's no need to extract anything - you already have a string.
I'm not sure what you're trying to do ... Why the char* ? Why the const char* ? Why not just std::string ?


>> 7. Assume user inserted an IP address into clientInput. When i want to validate it, the algorithm of validation
>> briefly will be as following:
>> a. convert the stream of chars into string
>> b. count the 4 dots
>> c. make sure other inputs are digits (excluding dot).
>> Do you have any suggestions?

If the inet_pton I suggested above doesn't do what you want, then you can parse the data manually. Just read 4 integers from the string separated by dots.
Regular expressions might also be interesting for you.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2009

Commented:
>>    char* abc = const_cast<char *>(input.c_str());

Be careful with that ... There's a reason that c_str() returns a const char*. In general you should be very wary about casting away const-ness.
jkr
CERTIFIED EXPERT
Top Expert 2012
Commented:
1) casting 'const' way is more than dangerous - if you change the contents, you might most likely get a crash. Try either

//********* 1 **********//
char clientInput[255];
string input;
getline(cin, input);
strcpy(clientInput, input.c_str());
//******** 1 **********//

or

//********* 1 **********//
#include <string.h>
char* clientInput;
string input;
getline(cin, input);
clientInput = strdup( input.c_str()); // 'free()' that later!
//******** 1 **********//

2. Apart from that being a const pointer - there is no storage space that it points to. Similar to the above, try

//******** 2 **********//
char clientInput[255];
string input;
getline(cin, input);
stringstream ss(input);
ss >> clientInput;
//******** 2 **********//

3. There is also one 'cin' member of 'getline()' that handles that, i.e.

char userInput[MAX_DATA];
cin.getline(userInput,MAX_DATA);

4. consider creating a function for that, e.g.

#include <stdlib.h>
 
bool get_num(char* p,int& num) {
 
  char* pcEnd = NULL,
 
  num = (int) strtol(p,&pcEnd,10);
 
  if (*pcEnd == '\0') return true; // valid number
 
  return false;
}

5., 6. and 7. - along the lines of the above function, you could write one, but why reinventing teh wheel? There is 'inet_addr()' (http://www.opengroup.org/onlinepubs/000095399/functions/inet_addr.html) that does that for you like

bool is_ip_addr(char* p) {

  unsigned long ul = inet_addr(p);

  if ( ul == INADDR_NONE) return false;

  return true;
}
jkr
CERTIFIED EXPERT
Top Expert 2012

Commented:
Ooops - race condition...
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> Ooops - race condition...

Aaaah, I was wondering why that was mentioned in the question ... Turns out F-J-K knew what was gonna happen heh ;)

Author

Commented:
Well done. It helped alot
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.