String Array Pointer in C++ Quiz Question with Solution


1.  Write a program in C++ that read a CString and discard all the symbols except the digits.converts the CString to an integer and store this integer in variable and print it. (10)
Sample Output:
Enter a CString:12ty12
String convert to integer:1212

Enter a CString:69$
String convert to integer:69

Hints:Use strlen,isdigit,atoi functions


Solution:

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
 char str[50];
 char intStr[50];
 int index=0;
 cout<<"Enter a CString :";
 cin>>str;
 for(int i=0;i<strlen(str);i++)
 {
        if(isdigit(str[i]))
          intStr[index++]=str[i];      
 }
 intStr[index]='\0';
 int value=atoi(intStr);
 cout<<"CSting to Integer :"<<value<<endl;
 system("PAUSE");
 return(0);  
}











2. What will be the output of this code? (5)

vector<int> v(5);
for (int k=0; k<v.size( ); k++)
  v[k]=k+1;  
for (int k=0; k<v.size( )/2; k++) {
          int temp = v[k];
          v[k] = v[v.size( )-k-1];
          v[v.size( )-k-1] = temp;
}
for (int k=0; k<v.size( ); k++)
  cout<< v[k]<<"  ";

 
5 4 3 2 1
 





3.What will be the output of this code? (5)

  int x, *p1, *p2;
  x   = 1;
  p1  = new int;
  *p1 = 5;
  p2  = new int;
  *p2 = 3;
  x  = *p2;
  p1 = &x;
  cout  << *p1 << " " << *p2 << " " << x << endl;
3 3 3