Hey people :) Write a *C++* program to print the ASCII code for the corresponding *string*. Pleaseeeee Hellppp!! :')
Funny thing about a string... if you convert it to a series of CHARs, those can be treated as INTs.
i know that's what we're supposed to do, but i'm just confused about HOW to do it :( I mean, I got perfect output in C , but c++ is just so freaking confusing :P
Here is an example I snagged: //std::string s char *a=new char[s.size()+1] a[s.size()]=0; memcpy(a,s.c_str(),s.size()); That is one way to do it.
In that, you make a char array that is the proper size to hold the string, then copy the string to it.
There is also strcopy.... or something like that. Let me find it.
And this is a nice, clean method: http://stackoverflow.com/questions/347949/convert-stdstring-to-const-char-or-char Pretty similar to the first I grabed.
Considering that C++ is a superset of C, a C solution is a C++ solution.
As long as you include the right things.
If all you must do is print the characters, you could simply create a for loop, iterate through the string and storing each index in an int and print to the screen. However, if you'd like to get creative you can always create a class to contain your char, the ascii value, and any other property you want.
Hi Aaddiittii! Here is code snippet of your "ASCII value" question:-- #include<iostream.h> #include<conio.h> #include<stdio.h> void main() { clrscr(); int i,j,l; char ch,str[10]; cout<<"Hi Aaddiittii! First of all, enter the length of your string:"; cin>>l; cout<<"Enter the characters of the string sequentially & its respective ASCII code:\n"; for(i=1;i<=l;i++) { cin>>ch; cout<<(int)ch<<"-"; } getch(); }
Join our real-time social learning platform and learn together with your friends!