QUESTION: please tell me if i want to use modulas and division operation on strings ten how can i do it. when i m compiling this  code i m getting an error illegal use of pointers but i want to use this in my program.how can i overcome this error.
class addrecord
char str1[10],rno[15];
void lcrd()

int i;
cout<,"\n enter roll no";
void main()
{ addrecord rd;

ANSWER: c-style strings are just arrays of characters, terminated by a null character.

Among the built in types, arithmetic operations are available only on numeric types like integers. These are not available on strings.

If the string contains numerals for digits of an integer, you should first convert it to an integral type and then on the resultant integer, modulus and division operations are possible.

Also, avoid the use of gets() in your code; The gets() function cannot be used securely, because of its lack of bounds checking, and the inability for the calling program to reliably determine the length of the next incoming line. The use of this function enables malicious users to arbitrarily change a running program's functionality through a buffer overflow attack. It is strongly suggested that the fgets() function be used instead.

---------- FOLLOW-UP ----------

QUESTION: if string is of type:-0903it071004 and i want to perform modulas and division operation on it. how can i perform?

If the C style string contains only numeric digits, here is one way (error checking has been elided) of converting it to an int:

#include <iostream>
#include <sstream>

int to_int( const char* cstr )
     std::ostringstream ostm ;
     ostm << cstr ;

     std::istringstream istm( ostm.str() ) ;
     int number ;
     istm >> number ;

     return number ;

int main()
     char cstr[] = "123456" ;
     int n = to_int( cstr ) ;
     std::cout << n%10 << '\n' ;


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2016 About.com. All rights reserved.