[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2009-02-14
7
Medium Priority
?
3,034 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

0
Comment
Question by:F-J-K
7 Comments
 
LVL 13

Expert Comment

by:josgood
ID: 23641829
>>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.
0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 1200 total points
ID: 23641831
>> 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.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23641838
>>    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.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 86

Assisted Solution

by:jkr
jkr earned 800 total points
ID: 23641877
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;
}
0
 
LVL 86

Expert Comment

by:jkr
ID: 23641882
Ooops - race condition...
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23641922
>> 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 ;)
0
 
LVL 1

Author Closing Comment

by:F-J-K
ID: 31546957
Well done. It helped alot
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The SignAloud Glove is capable of translating American Sign Language signs into text and audio.
If you are a mobile app developer and especially develop hybrid mobile apps then these 4 mistakes you must avoid for hybrid app development to be the more genuine app developer.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Introduction to Processes

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question