Friday, July 31, 2009

Op. 131 String Quartet in C# Minor by Beethoven?

Movement IV, It's the one in Band of Brothers





does anyone know a way i could get this a brass quartet?

Op. 131 String Quartet in C# Minor by Beethoven?
Due to the significant differences in the ranges of a trumpet and a violin, it would be difficult to pull this off. You can download a copy of the score, as it's public domain, from the link below and see for yourself.





However, if you really want to do this piece, I am a professional arranger and can see if I could create a workable version for you if you're interested. You would probably need at least one of your trumpet players to be good with a piccolo trumpet to make it most effective.


Reading text files in C++?

How can you read text and integers from a file in C++ and store them as strings and varibles for use in the program. The text file formated like string, string, string, int, int, int, int over serveral lines like below.





Word1 Word2 Word3 Int Int Int


Word1 Word2 Word3 Int Int Int





and so on...

Reading text files in C++?
fscanf()? http://www.cplusplus.com/reference/clibr...


Which is the best string searching algorithm in C# 2003?

the best algorithm which can be implemented in c# 2003 (.net framework 1.1.4322)?

Which is the best string searching algorithm in C# 2003?
palindrom like

blazing star

C++ help? (ten points to person with most answers)?

Is there a function in C++ to enter a string into a zip password and check if that string is the correct password?


Second, how can you:


get part of a string


change a string to uppercase


change a string lowercase





Thanks.

C++ help? (ten points to person with most answers)?
There exists no such function.


To get part of a string, you use the substr member function. Hence,


#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using namespace std;


int main()


{


string s = "Hello World!";


cout %26lt;%26lt; s.substr(3,5) %26lt;%26lt; endl;


return 0;


}


will print out five characters of string s, starting from the character at position 3. The outputted string will be "lo Wo".


To change a string to uppercase: loop through the string and consider each character in turn. If it is greater than or equal to 'a' and less than or equal to 'z', subtract 32 from its ASCII value.


To change a string to lowercase: loop through the string and once again consider each character in turn. If it is greater than or equal to 'A' and less than or equal to 'Z', add 32 to its ASCII value. Hence,


void convert_to_uppercase(string%26amp; s)


{


int i;


for (i=0; i%26lt;s.length(); i++)


if (s[i]%26gt;='a' %26amp;%26amp; s[i]%26lt;='z')


s[i]-=32;


}


void convert_to_lowercase(string%26amp; s)


{


int i;


for (i=0; i%26lt;s.length(); i++)


if (s[i]%26gt;='A' %26amp;%26amp; s[i]%26lt;='Z')


s[i]+=32;


}
Reply:No, there is no function in standard C++ to enter a string into a zip password and check if it is correct. You will have to use a C++ Zip library. I suggest you check out http://www.example-code.com/vcpp/zip.asp


You should be able to convert the MFC examples to C++ with no modification.





Idk about your second question.





Third is:


for(int i = 0;i%26lt;strlen(StringHere);i++)


{


if(StringHere[i] %26lt; 97){StringHere[i] =


StringHere[i]+32;


}


}


Last Question:





for(int i = 0;i%26lt;strlen(StringHere);i++)


{


if(StringHere[i] %26gt;= 97){StringHere[i] =


StringHere[i]-32;


}


}





That function is made from the fact that the lowercase versions of letters in ASCII are always the number of the uppercase + 32. You should be able to put the loops I just posted in a function, so you don't have to write all that everytime you wish to convert to lowercase or uppercase.





http://www.asciitable.com/


C++ Programing Help!, usinng 'string' function to create 'ofstream' file name!?

im doing a program for my class. i have to make a 'string' function that takes the name of the ifstream file (data1.txt) and the string function changes that string into 'data1.csv'.





that way, when i go to open my ofstream file (which doesnt exist, so it'll create it), i use the call of the string function so it creates the file 'data1.csv'


....


here is what my function looks like...


string newoutput (string filename)


{


string newfilename;


int p;


filename.find('.');


p=filename.find('.');


cout %26lt;%26lt; filename.substr(0,p) %26lt;%26lt; ".csv";


return newfilename;


}





...then when i go to open the ofstream file, i have it saying...





result.open (newfilename);





....





but it does not compile. i think it has something to do with the way my function is set up. idk if its outputing it right or not. if i change "result.open (newfilename);" to "result.open ("data1.csv");" then it works exactly how it want it to. but my teacher wants me to use the string function. can anyone help me?

C++ Programing Help!, usinng 'string' function to create 'ofstream' file name!?
Your function actually returns the empty string because note that you have not assinged anything to "newfilename" within that function. Also, have you declared "newfilename" before you used it in the following line of code:





result.open (newfilename);





Note that you need to declare "newfilename" before you use it in the previous line (declaring it within the function is not enough because its scope is going to be within that function only).





I have rewritten your code and here is what I have:





string newoutput (string filename)


{


string newfilename;


int p = 0;





p = filename.find('.');


newfilename = filename.substr(0,p) + ".csv";


return newfilename;


}





string filename = "data1.txt";


string newfilename = newoutput(filename);


result.open(newfilename);


C++ Programming (array and string)?

Can someone do this code for me, i apperciate if the code is complete and ready to built and execute; this are the instruction:





Write a program that asked the user to enter a string. Then the program should ask the user to enter a letter. The program should serach for that letter in the string the user entered and REMOVE it from the string.





For example if the user enter: This is the string test


The enters the letter T


The program should print out: his is he sring es





Make the input/output "Friendly" Tell the user what the program will do and so on...





A few important things:


-Declare the array for the string at least 50 chars long


-Use #define for the array sizes


-USE FUNCTIONS, use at least one function. I used one funstion that took the string the user entered, an array to store the new string and the char. The prototype loked like this :


void remove_char ( char * string, char * newstr, char ltr);

C++ Programming (array and string)?
its a suggestion


never order other to do sth


better request or ask politely


and be happy with wat they give ya
Reply:Are you testing us or asking for help??
Reply:please do it when you get strunded then let me know


I want a program in "C" Language that reads 2 names into 2 string parameters then replaces between them

hi all


guess thats easy for some ppl, but not for me....





i just want to create a simple program in "C" language that reads 2 names with scanf function then it puts them into 2 string parameters then it replaces the names in the parameters with each others........








thats all








Notice,,,, the names' length isn't limited !!





thanks alot

I want a program in "C" Language that reads 2 names into 2 string parameters then replaces between them
#include %26lt;stdio.h%26gt;





void main()


{


char[] first, second, temp;


printf("Enter string: ");


scanf(%26amp;first);


printf("\n");


printf("Enter string: ");


scanf(%26amp;second);


printf("\n");


temp = second;


second = first;


first = temp;


}

imperial

I need an actual example of how to write a 'float function' in Visual Studio 2005 for C++!!!!!!!!!!!!!!!!!!!!!

i have the program Microsoft Visual Studio 2005





i am using this in my computer science class





i know how to properly write a 'string function' in C++ but in my homework assignment we need to write a 'string function' and a 'float function' and i have no idea what im doing wrong





i do exactly the same thing i do w/ the 'string function' to the 'float function' but it wont compile and i dont understand what the error is trying to tell me to fix, please god someone help me!!

I need an actual example of how to write a 'float function' in Visual Studio 2005 for C++!!!!!!!!!!!!!!!!!!!!!
When you ask a question like this in the future, it might help to also post the error that you get when compiling your code. It actually can tell you a lot!





Based on the code you posted, I see a couple of problems:





1) You function signature: float findarea (float h, float a, float b);


Doesn't match your function definition: float findarea (float h, float a, float b, float area)





That will be a problem. Looks like you can eliminate the 'float area' variable and they should match then. Remember that the signature you put at the beginning of your code needs to match the function you write later on!





2) when you call findarea: cout %26lt;%26lt; findarea;


You are not passing any of the variables! You need to send the variables to the function for it to do any work. You probably want: cout %26lt;%26lt; findarea(h, a, b);





3) Finally, in the function itself, you do work on the variable 'area' but you return an unitialized variable 'testarea'. You probably want:





float findarea (float h, float a, float b, float area)


{


return ((1/2)*(h))*(a+b);


}








If you still have problems, you probably should post a new question with the part of the code that matters and the error messages that you are seeing when you compile. But I think these three changes will compile OK for you (assuming you make the same kind of changes to your other functions). There is nothing special about float functions, you just need to brush up on the rules for writing functions in general.





Good Luck!
Reply:Can you post your code? Do you just need a function that handles floating point numbers?





float division(float x, float y){


return x/y;


}





int main(){


cout%26lt;%26lt;division(10,3)%26lt;%26lt;endl;


}
Reply:Edit your question and put in the code you are trying to use...we can't really help you with your errors unless we see the code. This also allows people to see that you did give it some effort and you need help rather than looking for homework answers.


Convert string to integer in C, without using itoa function?

Basically, I want to know what's "behind" itoa... A site which explains/expands functions in C would be useful, too.

Convert string to integer in C, without using itoa function?
void itoa (char *buf, int base, int d)


{


char *p = buf;


char *p1, *p2;


unsigned long ud = d;


int divisor = 10;





/* If %d is specified and D is minus, put `-' in the head. */


if (base == 'd' %26amp;%26amp; d %26lt; 0)


{


*p++ = '-';


buf++;


ud = -d;


}


else if (base == 'x')


divisor = 16;





/* Divide US by divisor until UD == 0. */


do


{


int remainder = ud % divisor;





*p++ = (remainder %26lt; 10) ? remainder + '0' : remainder + 'a' - 10;


} while (ud /= divisor);








/* hex values */


if(base == 'x')


{


*p++ = 'x';


*p++ = '0';


}





/* Reverse it */


*p = 0;


p1 = buf;


p2 = p - 1;


while (p1 %26lt; p2)


{


char tmp = *p1;


*p1 = *p2;


*p2 = tmp;


p1++;


p2--;


}


}
Reply:I don't know what is behind itoa... however, I did oncewrite a c function to convert integer to individual asci codes, then display it using my own little text system for GBA using HAM





here is the smaller one, does 4 digits from an unsigned 16 bit number...





void Draw_4dd(u16 num,u8 nx,u8 ny)


{


if(num%26gt;9999)num=9999;





u16 Th=0;


u16 Hu=0;


u16 Te=0;


u16 On=0;





Th= (num/1000);


Hu= ((num-(Th*1000))/100);


Te= ((num-(Th*1000)-(Hu*100))/10);


On= (num-(Th*1000)-(Hu*100)-(Te*10));





Th=Th+48;


Hu=Hu+48;


Te=Te+48;


On=On+48;





if(num%26gt;999)


Draw_Text(Th,nx,ny);


if(num%26gt;99)


Draw_Text(Hu,nx+1,ny);


if(num%26gt;9)


Draw_Text(Te,nx+2,ny);


Draw_Text(On,nx+3,ny);


}





u16 and u8 are unsigned 16 and 8 bit vars. I break the number down into ten's place values, then add the code for 1(48) to them(giving me the asci codes for the numbers), then pass it to my single charector text plotter function Draw_Text I was going to write a faster version of this, but never got to it. the only thing that makes this work is the fact that integer values don't keep a decimal value. when you divide 1234 by 1000, you still get 1 as a result. multiply back by 1000, you get 1000. the fact that the computer is in 2 base is irrelevant, because i use a seperate var for each 10 place value.





converting string to integer would be the same thing backwards





what I would do is treat the string as an array, walking through each char, from the end to the front, multiplying each new number by the next ten power, then adding it to an accumulating integer variable. You would also have to look for indicators, like spaces, commas, dollar signs, and bad data, like letters...





hope this helps a little.
Reply:Ok... 124 = 100 + 20 + 4. In other words, 124 = 1*100 + 2*10 + 4*1. Get the idea?





The actual source code should have a more efficient algorithm, probably with binary math, logical shifts, shortcuts, etc. It could even be written in assembler. Many compilers do include the source code of their libraries.


Convert string to integer in C, without using atoi function?

Basically, I want to know what's "behind" atoi... A site which explains/expands functions in C would be useful, too.

Convert string to integer in C, without using atoi function?
Here is the simplest example. It's a bit clumsy as it doesn't check for overflow:





int my_atoi ( const char * s )


{


int n = 0;


if(!s) return 0;


while(*s)


{


if(*s%26lt;'0' || *s%26gt;'9')


return 0;


n = n * 10 + *s - '0';


s++;


}


return n;


}
Reply:just substract each character by '0'


What strings should I get for my cello?

I have a relatively bright cello. Right now I have Larsen A%26amp;D and Helicore G%26amp;C. I'll be changing strings right about christmas time, and I'm trying to figure out what kind of strings to get now. I was thinking about obligato, or a mix of obligato and oliv or evah. I was just wondering if anyone knew a site with cello string reviews, or has personal experience themselves. Thanks!

What strings should I get for my cello?
I would stick with Larsen A%26amp; D but switch to Prim for G%26amp;C they seem to balance very well (big bottom and bright top now that's a sight) I am very VERY happy with the Prim ... I switched to Larsen last year after many years with Jargar on top ... liked the change
Reply:www.amazon.com


i think obligato is one of the best brand for strings...
Reply:I always found Yargar strings to be the best for my cello. i have always liked the sound they produced and they seem to hold out really well for me also.

elephant ear

Character String Help in C?

I have a problem with character string manipulation, im trying to prompt the user to enter a float (i.e. a numerical value) but the user can decide to close the program if he/she enters "exit". I tried using the isdigit and isalpha functions, but they only return a value of 0, which would force me to re-prompt the user. Any suggestions on how to immediately quit the program once the user enters "exit" ?

Character String Help in C?
Read in the character array (string) value and then test it being equal to exit. If not, then use the atof() function to try and convert the value to a float.





For example,





char myChar[20];


float myVal=0.0;


scanf("%s",myChar);





if (strcmp(myChar,"exit")) {


/* input is NOT equal to exit */


myVal = atof(myChar);


...





myVal would then contain the numerical value of their input according to the conversion rules of atof().





(massiv_x: a "string" is a character array terminated by a null character; what you've given is actually in error because you've defined 27 bytes, BUT because the value is enclosed in double-quotes, it stores 28 bytes (including the null terminator.) You can't use any string functions with that variable as it doesn't contain space for the string terminator \0. Perhaps just a typo. ;)
Reply:if i recall...the isdigit and isalpha function take only a single value...





in c, strings are actually just character arrays...you know:


char thisstring[27] = "twenty-seven bytes of data.";





in order for your method to work, youll have to pass in every letter on by one...this wont work for your cause tho..


when you pass the values into isalpha or isdigit you have to use the array index with the string variable..if you dont, youre just passing in a memory pointer value..this may work for you, you just gotta access the array (string) directly from memory using pointers..


How do you do a string compare with a switch case? (a c++ question)?

This is a c++ question, is the only way to do a string compare is an if else if statement or can I do a switch case?


I want to change this following statment to a switch case, could it be possible?


if (strcmp (open,"opendoor") == 0)


{ cout%26lt;%26lt;"It's locked."%26lt;%26lt;endl;}


else if (strcmp (open,"closedoor") == 0)


{ cout%26lt;%26lt;"It's already closed") == 0)}


else if (strcmp (open,"backward") == 0)


{ lvl3();}

How do you do a string compare with a switch case? (a c++ question)?
int flag ;


String x;


.


. //somewhere in the code make x take the value of "opendoor", "closedoor", or "backward"


.


flag = strcmp(open,x);


switch x{


case "opendoor":


if (flag == 0) cout%26lt;%26lt;"its locked"%26lt;%26lt;endl;


break;


case "closedoor":


if (flag == 0) cout%26lt;%26lt;"its already closed"%26lt;%26lt;endl;


break;


case "backward":


if (flag == 0) lvl3();


break;


}


Tension: A light inextensible string AB of length 2L has a particle attached to its mid-point C...?

A light inextensible string AB of length 2L has a particle attached to its mid-point C. The ends A and B of the string are fastened to two fixed points with A at an distance L vertically above B. With both parts of the string taut, the particle describes a horizontal circle about the line AB with constant angular speed omega, w.





If the tension in CA is three times that in CB, show that w = 2√(g/l).





I thought I'd worked it out, but I keep getting back to w = 1.32√(g/l). From that, I think I've resolved the forces wrongly - but if C is a mid-point, that means the length of CA should be = length of CB, right? From there, doesn't it also mean that cos theta = (L/2)/L? I don't really understand; help'd be very much appreciated. Thanks so very much in advance!

Tension: A light inextensible string AB of length 2L has a particle attached to its mid-point C...?
Yes, I think that you are forgetting the vertical component due to the tension (T) in BC.





Resolving vertically: mg + T cos theta = 3T cos theta


mg = 2Tcos theta





As you say cos theta = (L/2)/L = 1/2





Thus mg = T


m = T/g ............Eq (1)





Resolving horizontally: mrw^2 = 3T sin theta + T sin theta


but r = L sin theta


Thus mw^2 = 4T/L





Substitute for m from (1) and rearrange





w^2 = 4g/L





Hope that helps.
Reply:You get the given result only iff the line (not a string) AB has length L.


Summing horizontal forces gives:


m*r*w^2 = (3F + F)*sin(fi)...........(1), and


summing vertical forces gives:


m*g = (3F - F)*cos(fi)..........(2)


where:


F is the lower string force,


fi is the angle between AB axis and the upper string,


r is the radius of the mass (distance from AB axis),


L is the length of AB axis.


Dividing (1) by (2) gives:


(r/g)*w^2 = 2*tan(fi) = 2 * r/(L/2) = 4*r/L giving:


w = 2*sqrt(g/L).


Drop C tuning?

I know how to tune to drop C. However, do I need special strings for a drop C tuning? I really don't want to take my guitar out of tune and find out that there is too much slack to play.

Drop C tuning?
I assume you are playing an electric guitar.





If you are using light strings (9 - 42) then you really really need thicker strings.


For a drop C you should use 11s.





You can do it with thin ones but it'll be very loose, buzzy, and the notes will be in and out of tune.


I've heard guys do that - it has a certain effect - not my cup of tea.





Also, you need to make sure your pickups aren't too close to the strings.


With the lower tension, the magnetic field can make the low notes sound like something is very messed up.





There's no harm in trying. See if you lke it.


When you say you don't want to take your guitar out of tune, it makes me think you must be a beginner - get an electric tuner and don't worry.
Reply:No, as far as I know you don't need to have any special strings, least I don't use any.
Reply:for drop c i would use size 11-50 bigger strings work better for the low tunings you may have 9-46 on your guitar now...

lady palm

String operations in C# ????

How can I do the following :


if for example i have a string entered by the user in this format:


AX, BX


or AX , BX


or AX ,BX





what can i do so that i can neglect any spaces eneterd by the user so that each time whatever the user enters it will look like this : AX,BX ???

String operations in C# ????
What you want to do is to replace all white spaces with the empty string. Here is how you can do that:





string something = "AX , BX";





something = something.Replace(" ", "");





// or


something = something.Replace(" ", string.Empty);
Reply:1. call a string tokenizer with the parameter(,).


2. as you read each token trim it for leading and trailing white spaces


3. to a common string append the token and "," to it incrementally for all the tokens.
Reply:string myString = "AX, BX";


myString = myString.Replace(" ","");


C++: get the name of the user, then insert it into a string?

Here is supposedly the code to get the name of the current user:








char acUserName[100];


DWORD nUserName = sizeof(acUserName);


if (GetUserName(acUserName, %26amp;nUserName))


{


cout %26lt;%26lt; "User name is " %26lt;%26lt; acUserName %26lt;%26lt; "." %26lt;%26lt; endl;


}


else


{


cerr %26lt;%26lt; "Failed to lookup user name, error code " %26lt;%26lt;


GetLastError() %26lt;%26lt; "." %26lt;%26lt; endl;


}





But when I compile it, I get this error:





error C2664: 'GetUserNameW' : cannot convert parameter 1 from 'char [100]' to 'LPWSTR'


Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast





Once this error is fixed, I would then like to use it to place into the string of a file path. For example: "C:\Username\Documents and Settings"

C++: get the name of the user, then insert it into a string?
I agree with Einstein:





This compiles and runs fine:





#include %26lt;iostream.h%26gt;


#include %26lt;windows.h%26gt;





int main()


{


char acUserName[100];


DWORD nUserName = sizeof(acUserName);


if (GetUserName(acUserName, %26amp;nUserName)) {


cout %26lt;%26lt; "User name is " %26lt;%26lt; acUserName %26lt;%26lt; "." %26lt;%26lt; endl;


}


else {


cerr %26lt;%26lt; "Failed to lookup user name, error code " %26lt;%26lt;


GetLastError() %26lt;%26lt; "." %26lt;%26lt; endl;


}





return 0;


}





The only difference can be the includes.
Reply:Check out http://www.pscode.com for great source code samples - I don't do C++ (I'm a VB programmer) but I use the site all the time.
Reply:You have a problem with your #include directives. Apparently you are mixing the old iostream headers with the Standard C++ Library headers. This causes the compiler error C2664.





Mixing the old iostream headers with the Standard C++ Library headers is not recommended.





----





I don't know if the below work-around will fix the problem...





Try changing:





cout %26lt;%26lt; "User name is" %26lt;%26lt; acUserName %26lt;%26lt; "." %26lt;%26lt; end1;





To





std::cout %26lt;%26lt; "User name is" %26lt;%26lt; acUserName %26lt;%26lt; "." %26lt;%26lt; end1;
Reply:string name; //declares a string


cin%26gt;%26gt;name; //inputs a name


Explain how you can produce a low pitched note on a guitar by altering a.length b.tension c.thicknes of string

a. length


Altering the length means that the verticle distance that the string has to move during vibrations is longer, hence it takes more time. Frequency, tone is proportional to 1/time.





b. tension


A looser string means that the force in the verticle direction is lower so that the force takes longer to pull the string back. Slower means more time.





c. thickness


A thick string has higher mass so that the force from tension takes longer to pull the string.


What is the C's realloc() equivalent in C++?

char *string = new char[10];


...


delete [] string;





is the C++ equvalent to





char *string = (char*)malloc(10);


...


free(string);





How can I realloc() the string to 20 characters, preserving its contents?

What is the C's realloc() equivalent in C++?
There isn't a realloc() or a redim() in C++. You have to declare a new char[20]. Copy the old one to the new one. And finally, delete the old one.
Reply:with built-in functionality you can't...you want to use one of the common libraries such as cstring which can do resizing etc.
Reply:In C++ you can use STL's as these inbuilt data structures does a lot of work with minimal code.

snow of june

C++ taking input and comparing it against a string?

I'm working on coding a c++ program but i'm having a few problems. Bassically i'm trying to copy the contents of a input text file in to a string, and then allow the user to input a word or string of the user's own to cross reference with the input string from the file and show the index where it first occured.





Thus far i've been able to get the contents of the input file in to the string, but i can't figure out what i'm doing wrong as far as taking the user's string and comparing it.





// user_word is holding the input string from user





int i = hold_all_text.find(user_word);





if(i != string::npos) {


cout %26lt;%26lt; "Found match for your word " %26lt;%26lt; user_word %26lt;%26lt; " at " %26lt;%26lt; i %26lt;%26lt; endl;


}


else


cout %26lt;%26lt; "No match in file contents.\n";


return 0;





Going in to the debugger it just shows the value of "i" as being -1





If anyone could help i would greatly appreciate it, i've been trolling around forums but i cannot seem to find anyone who is having exactly the same issue

C++ taking input and comparing it against a string?
The only thing I can think of is your strings hold_all_text and user_word do not contain what you think they do. The result you're getting is telling you hold_all_text does not contain user_word, and that's probably true. See the simple example below that I wrote to illustrate, it does what you're trying to do, and it works.





Some suggestions:


It might be better to read the contents of the file into a vector%26lt;string%26gt;, then you can report line number and position in the line for strings to be found.


Even if you don't use a vector, you should do your search in a loop, to find all occurrences of user_word. The version of find you're using, that I use below, takes an optional pos argument, the index to start the search. You can use this to continue searching in a string after you've found the first occurrence of the substring.





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main(int argc, char *argv[]) {


string s0("the quick brown fox jumped over the lazy dog");


string s1;


size_t loc;





cout %26lt;%26lt; "s = " %26lt;%26lt; s0 %26lt;%26lt; endl;


cout %26lt;%26lt; "Enter substring to find: ";


getline(cin, s1);


cout %26lt;%26lt; "\"" %26lt;%26lt; s1 %26lt;%26lt; "\"";


if ((loc = s0.find(s1)) != string::npos) {


cout %26lt;%26lt; " found at index " %26lt;%26lt; loc %26lt;%26lt; endl;


} else {


cout %26lt;%26lt; " not found." %26lt;%26lt; endl;


}


return 0;


}


Program in C to extract a portion of character string and print the extracted string.?

program in C to extract a portion of character string and print the extracted string. assume that m characters are extracted, starting from the nth character.

Program in C to extract a portion of character string and print the extracted string.?
//caution: modifies inbound string param "s"


char *strext(char *s, int n, int m)


{


s[n+m-2] = '\0';


return %26amp;s[n-1];


}





main()


{


char *str = "This is my test string to check the program";


puts(strext(str, 6, 12));


}
Reply:That sounds like a homework assignment. Why don't you TRY IT YOURSELF first, and when you're stuck, post your code so we can comment on it?


How to make a palindrome program in turbo c without using string.h?

this is a tough project for me can anyone help me

How to make a palindrome program in turbo c without using string.h?
First define what you want your palindrome program to do. If you want a real challenge you can get it to construct witty sentences like "Go hang a salami, I'm a lasagna hog."

bottle palm

How to compare variables in c without using string compare (strcmp)?

i've assigned a certain value on a variable... and then i get input from the user, how will i compare the variable value to the input???

How to compare variables in c without using string compare (strcmp)?
If you mean to compare a number entered via the keyboard which is stored in a string to a value store in say an int then you need to convert the number in the string.





int userval, aval;





aval = 10;


sscanf(buf, "%d", %26amp;userval);


if (aval == userval) {


do something........


}


/* Where buf is the string entered */


Note this assumes the value is at the start of the buffer!





You can scan the input from the user directly into the var :-


scanf("%d", %26amp;userval);
Reply:A string in C is simply a pointer to characters, terminated by a null (zero) byte. All strcmp is doing is iterating over the strings comparing characters until it encounters the end of either string.





The following function is equivelent to the standard library function strlen, including the return value.





int compareStrings(const char* a, const char* b)


{


while (*a == *b++)


if (*a++ == 0)


return 0;


return (*(const unsigned char *) a - *(const unsigned char *) (b - 1));


}
Reply:You can use Array to Compaire.


Write a program in c++ to find string palindrome?

It would be more efficient to just inspect the string and work towards the middle.





1) Create a for loop similar to this one...


i =0; i %26lt; (string.length / 2); i++





2) Inside the loop, compare string[i] to string[string.length - i]


If the values are the same, your string may be a palindrome, continue. If the values aren't the same, it's not a palindrome, break; the loop.





The suggestions above are pseudo-code, but should be helpful. Another thing to keep in mind, is to make sure you convert the characters you are comparing to either be both upper-case or both lower-case. "Racecar" would fail if you don't because the string(or character) "r" does not equal the string "R".





Good luck.

Write a program in c++ to find string palindrome?
Think of the word Racecar. If you spell it backwards it spells Racecar.





Have two variables, One holds the word, the other is the reverse order of the same word. If the two variables are the same then return 1, yes, true, etc. etc.





Use two arrays to store the data and a pointer to read the


array backwards.





There's your hint.





- Hex


How do you store a group of characters, say the 2nd thru 9th in row 2, in a text file as a string in C?

I'm a professional PHP developer, and it's been a long time since C, so I'm not going to run this through a compiler now, but it goes something like this:





#include %26lt;stdio.h%26gt;





int main() {





FILE *fp;


char mystr[] = "This is my very awesome string."


char *myotherstr = %26amp;mystr[1];





fp = fopen("out.txt","w");


fwrite(fp,myotherstr,7);


fclose(fp);





return 0;


}


Write program in C that transfers string "Hello" to connected computer, the receiver should respond with "Hai"

u need to search messaging in c++ and study

Write program in C that transfers string "Hello" to connected computer, the receiver should respond with "Hai"
I'm *guessing* at the question here. I'm supposing that there are two computers and you want one to send the other the word "Hello" and the other to send back the word "Hai".





There's a few ways of doing this, but underneath it all it boils down to sockets in some form or other.





I won't write out the code explicitly (a bit of digging around followed by some trial and error on your part and you should have it working quite quickly)





For the purposes of this example, suppose there's a 'remote' computer and you want it to run a TCP listening 'service' or whatever you want to call it.





open a socket (tcp=SOCK_STREAM)


bind to the socket


listen on the socket


accept on the socket


recv some bytes


check those bytes are "hello"


send "Hai"


close the socket





Here's your 'local' client:


open a socket


connect to the socket


send "Hello"


recv some bytes back


close the socket.
Reply:sound to me you are taking on a basic c program language. that is what they all teach you in tech class. your basic "hello" programs.
Reply:This also sounds like something you'll want to find out how to do yourself, so that when the instructor tests you on the concepts you won't be clueless and then fail the exam and eventually the class, and later get fired from a job for not knowing how to do something you said you could but really didn't because you didn't do your own homework and practice the concepts yourself.

magnolia

Why does C++ have a string class when there is already char * (a pointer to type character)?

A string is much more easier to work with than the char * due to the following reasons:


1. You have strict bounds checking in strings; char * doesn't have that.


2. If you need to equate two strings, you can just use the = symbol, not have to call the strcpy function everytime.


3. you can check for equality in an if condition ie u can use == to check if two strings are equal.


4. You can access individual characters by using the .at().


5. You needn't call strlen to check the length. all that need to be called is stringvariable.size().





There are a lot other advantages of using string class too. Ultimately, the string class scores on the ease of use. The char * scores on the raw power that it provides. You can use either depending upon your requirement and the time you are ready to devote to coding.

Why does C++ have a string class when there is already char * (a pointer to type character)?
Char is a single entity.......'a' , '1' etc.





But if u have a collection of characters together....."Bombay","computers"......


That is a string.


the space occupied is more 4 strings whereas character utilises only one byte.





Also way of use 4 chars and strs are different.String handling has a very huge application.However ,it should be noted that a string is an array of characters.


And use is so extensive that use of pointers can be sometimes tedious for the use of strings and is not always convenient and so we deal with string class independently though pointer can be used too.
Reply:char* strings are known as C strings. The usage of C strings is considerably more complex, not least because you have to be aware of memory issues.





With C++ strings for example, you can concatenate strings or place new strings in a string variable with little thought for the underlying memory handling. With char* strings, you better be aware of issues such as null-character termination, having enough buffer space when concatenating, and so on.





In short, C++ strings is a level or two above C strings in abstraction.


Which of the following is NOT a primitive data type in C?

A. int


B double


C short


D string

Which of the following is NOT a primitive data type in C?
string
Reply:String.
Reply:string


Is there a syntex on C# to convert from "int" to "string"?

in C# the compiler does an automatic conversion from "int" to string"......I just want to know is there a syntex to do it as the opposite syntex "int.parse(string)"

Is there a syntex on C# to convert from "int" to "string"?
you call Convert.ToInt16 or Convert.ToInt32.





http://msdn2.microsoft.com/en-us/library...
Reply:Look at the properties for the int type.





int foo;


string bar;


bar = foo.ToString();


Some c++ coding doubts(string stream)?

can you please explain in detail what the followinf code does?


especially what does the fgets,sizeof,and sscanf do?





char buf[50];


int option;





fgets (buf, sizeof(buf), stdin);


sscanf (buf, "%i", %26amp;option);

Some c++ coding doubts(string stream)?
fgets-: reads a string from a file


sscanf-:reads formatted input from a string


sizeof :- u have to enter the no of bits u want too use
Reply:stdin is a buffer between either the terminal or the DOS prompt. fgets is just getting what ever is in the then sscanf is putting it in option. Its a round and about way of asking for user input

forsythia

In C# given a string naming an enum how do you get the type? Type.GetType doesn't seem to cut it!?

?

In C# given a string naming an enum how do you get the type? Type.GetType doesn't seem to cut it!?
Check out Enum.Parse() method:





http://msdn2.microsoft.com/en-us/library...


I cant understand pointers and structures in C programming?

i know the basics but can anyone tell me tricks and basic things to remember for sure. i get confused when it comes to pointers and arrays and there connection and when to use *p and when to use %26amp;p and when not to. can anyone summarize the rules and common mistakes with pointers and structures in C programming. Also string literal basics as well. Thanks.





Whateveryou can explain will definitely help!

I cant understand pointers and structures in C programming?
Homestar is right as far as he goes. He uses a type called "string" which wasn't part of the ansi c language last Og checked - and quite frankly, strings, char arrays, are almost everybody's first introduction to the finer points of pointers vs the object to which the pointer refers. Og like to suggest picking up a copy of K%26amp;R (because it's thin and pretty easy to understand) and maybe suggest you throw references into the mix (references keep you from making 'stupid' mistakes with pointers - things like freeing memory that you shouldn't).





Everybody write this once:





char *myname = "Og";


char[] firstName = "Og";


char[2] alsoFirstName;


strncpy( alsoFirstName, myname, strlen(myname) );





printf( "myname: %s\n", myname ); // s.b. ok


printf( "firstName: %s\n", firstName ); // also ok


printf( "alsoFirstName: %s\n", alsoFirstName ); // oops!





Why does that third one fail? Because the array doesn't actually have space allocated for two characters plus one terminator (\0) symbol.





Note the different forms of initializing a string pointer, as well (all three variables can act like a char const*). In the first case the string (the two letters 'O', 'g' and the terminator) are kept in some data segment that never changes. In the second and third examples, the string is stored on the stack.





Anyway, this is pretty deep topic. Maybe e-mail work better. Barring any real concrete examples just remember: const and %26amp; (reference type) are your friends.
Reply:Structures are a collection variables under a name.Each variable within the structure can be accessed using the '.' mark.


An example would be this





struct profile{


string name;


int age;


}person1;





As you can see i have created a new structure called Profile and a new instance of this structure called person1.Now if i want to store anything about person1 i would do it like this.





person1.name = "Joe Schmoe"





As you can see i use the '.' mark to access the variables within the structure.Hope that helps you.





As for arrays,they are also a collection of variables,however they all have one datatype.To declare an array i do so.





int age[2]





The number within the square brackets indicates i want two integers named age.


To access each part of this array you also use the square brackets.However you must start counting from 0 when you want to access an array.Below is an example of me initializing both these integers.





age[0] = 65;


age[1] = 23;





I hope you understood me clearly ^_^.





Im not very good with pointers so bare with me.


A pointer points to a space in memory,a pointer will store this place in memory as an address.Declaring a pointer is as easy as declaring any other datatype,but you must place an asterisk (*) after the datatype.





e.g int* my_pointer;





Now to use this pointer we must assign it the address of another variable.For example say we had a variable called "age".To point to this variable in memory we must precede its name with the Ampersand sign (%26amp;).





e.g my_pointer = %26amp;age ;





Now if we were to output this pointer,it would give us the memory address of the variable age.





EDIT:Sorry i code in c++ i forgot to not use strings,however you should understand how structures work :)
Reply:OK... three questions in one.





Firstly pointers. Pointers aren't variables - but they do point to them. Pointers are defined using a * between the type and the variable, for example:


int *pointer


or


int* pointer





The latter makes more sense, as you're defining a pointer to an integer, and not an integer. However, it can cause confusion if you define normal integers on the same line, for example:


int *pointer,variable


or


int* pointer,variable


both define pointer as a pointer to an integer, and variable to an integer.





Pointers let you have multiple instances of the same variable. For example:


int i=3; /* initialise an integer */


int *p; /* create an integer pointer */


p=%26amp;i; /* and point it to the address of i */


*p=5; /* set value of integer pointed to by p, to 5


printf("%d %d",i,*p); /* print out value of both variables */





Not too useful, since I could have just used i and not the pointer? True. However, this comes into its own with allocated blocks of memory and (more simply) arrays.





See http://www.cprogramming.com/tutorial/c/l... for more details.





Next, structures. Basically, a group of variables tied together. For example, you could have an address-book with a structure 'addressBookEntry' for each entry, and within the structure you could have a name, address, phone-number, etc - but which could be referenced by a single variable name (or array) so that all the associated data is kept together within the same structure. Like a box.





I'll point you at the same site, next chapter for more info.


http://www.cprogramming.com/tutorial/c/l...





Finally, string literals. These are defined within source-code as the value of a quoted string. For example:


"This is a string literal"





Again, more info at the same site:


http://www.cprogramming.com/tutorial/c/l...


C++ What does string(3, ' ') do?

creates a string which consists of 3 spaces.


Sample program in C that implements STRING CONCATENATION using "strncat"?

Please provide me a sample program that implements String Concatenation using strncat. Thank you so much.

Sample program in C that implements STRING CONCATENATION using "strncat"?
http://www.wilsonmar.com/1strings.htm is a good source

jasmine

How to write a program in C by turning a hexadecimal to a decimal?

im having a hard time with this right now. help





write a c program that utilizes strings and numeric conversions





1. Read strings using a function you write called getStr ().


2. Write a function named hextodecimal () that takes in (only) a string parameter representing a positive hexadecimal number and return its decimal equivalent (integer). This function returns -1 if the string provided connotes to a negative number and/or is comprised of invalid characters.


-note: you may not use any library functions in this function- you must write all code necessary to enact the coversion and return the appropriate result.


-this function must accept both upper and lower case versions of the hex character.


-You may want to write an additional function that vets any string for invalid hex character


3. If original string is invalid, output an unambiguous message to the user and prompt for another input.


4. Output the original String, followed by its decimal equivalent. Clearly label which is which

How to write a program in C by turning a hexadecimal to a decimal?
I don't want to give you the entire solution, but I will give you some pieces to help, and comments where you need to fill in the code. This assignment justifiably restricts you from using library functions, which you would normally use to do much of the work for you. Use of fgets to get the user input is, I assume, allowed.





Note that I put the validity check in getStr, but part 2 of the problem statement wants you to check validity in hextodecimal, which is probably a better place to put it.





#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;





typedef enum { false = 0, true } Bool;





double Pow(const double x, const unsigned y);


int AtoI(const char c);


Bool isValidHexChar(const char c);


Bool getStr(char *s);


int hexToDec(char *s);





#define MAX_STR 256





int main(int argc, char *argv[]) {


char s[MAX_STR];





memset(s,0,sizeof(s));


if (getStr(s) == false) {


puts("\ninvalid entry");


} else {


printf("\n%s = %d\n",s,hexToDec(s));


}


return 0;


}





Bool getStr(char *s) {


char *p = s;


Bool isValidFlg = true;





/* prompt for hex value and read it using fgets */


/* remove '\n' from end of entered string */


/* loop for each character in the string, */


/* calling isValidHexChar( ) to check validity */





return isValidFlg;


}





int hexToDec(char *s) {





/* loop from the last char in s to the first, */


/* calling AtoI and Pow as you go to convert */


/* from hex to decimal */





return result;


}





double Pow(const double x, const unsigned y) {


double result = 1;


int i;





if (y %26gt; 0) {


for (i = 0; i %26lt; y; i++) {


result *= x;


}


}


return result;


}





int AtoI(const char c) {


int i = -1;


if (isValidHexChar(c) == true) {


if ((c %26gt;= '0') %26amp;%26amp; (c %26lt;= '9')) i = (int)c - 0x30;


else if ((c %26gt;= 'a') %26amp;%26amp; (c %26lt;= 'f')) i = (int)c - 0x57;


else i = (int)c - 0x37;


}


return i;


}





Bool isValidHexChar(const char c) {


Bool validFlg = false;


if (((c %26gt;= '0') %26amp;%26amp; (c %26lt;= '9')) ||


((c %26gt;= 'a') %26amp;%26amp; (c %26lt;= 'f')) ||


((c %26gt;= 'A') %26amp;%26amp; (c %26lt;= 'F'))) {


validFlg = true;


}


return validFlg;


}
Reply:try to avoid hexadecimal value....


How to write a program in C by turning a hexadecimal to a decimal?

write a c program that utilizes strings and numeric conversions





1. Read strings using a function you write called getStr ().


2. Write a function named hextodecimal () that takes in (only) a string parameter representing a positive hexadecimal number and return its decimal equivalent (integer). This function returns -1 if the string provided connotes to a negative number and/or is comprised of invalid characters.


-note: you may not use any library functions in this function- you must write all code necessary to enact the coversion and return the appropriate result.


-this function must accept both upper and lower case versions of the hex character.


-You may want to write an additional function that vets any string for invalid hex character


3. If original string is invalid, output an unambiguous message to the user and prompt for another input.


4. Output the original String, followed by its decimal equivalent. Clearly label which





with ASCII of ‘0’=48; value of ‘A’=65

How to write a program in C by turning a hexadecimal to a decimal?
suggest you post a code sample of what you have done already. this way people can help you and not GIVE you the answer.


Sample program in C that implements STRING CONCATENATION using "strcat".?

Please provide me a sample program that implements String Concatenation using strcat. Thank you so much.

Sample program in C that implements STRING CONCATENATION using "strcat".?
if i remember right, should be simple.





--------------------------------------...





char str1[20]="hello ";


char str2[]="world";





strcat(str1,str2);





printf("%s\n",str1);





------------------------------------
Reply:http://www.wilsonmar.com/1strings.htm is just what you want my friend,enjoy!...


Pic c program for serially outputing a string to a pc using hyperterminal for pic 16f877?

i need to output a string serially to a pc and get signals from pc like pressing' enter' key in the keyboard. so i need a pic c program for doing this using 16f877

Pic c program for serially outputing a string to a pc using hyperterminal for pic 16f877?
Once again... put your question in lay-mans terms.

crab apple

What strings are being plucked?

What strings are being plucked in this?





http://youtube.com/watch?v=ZokY2WrA9W4





I know the chords are Am F C G but what strings are being plucked with each note? It would be really helpful. For example "Am: 1 and 2 at the same time, then 4, then 3." "F: 2, 3, 4 and 5 at the same time".





Something like that, i just did that randomly.

What strings are being plucked?
you probably later figured out this was tennis but i play guitar too try this http://www.ultimate-guitar.com/tabs/o/on...
Reply:This is the tennis section. Ask this in the entertainment and music category in the list on the side of the page.


What strings are being plucked?

What strings are being plucked in this?





http://youtube.com/watch?v=ZokY2WrA9W4





I know the chords are Am F C G but what strings are being plucked with each note? It would be really helpful. For example "Am: 1 and 2 at the same time, then 4, then 3." "F: 2, 3, 4 and 5 at the same time".





Something like that, i just did that randomly.

What strings are being plucked?
I'm not being rude, but the video is as clear as daylight.





You can figure this out on your own.
Reply:well,it depends on how you want the chord to sound like when playing a particular song..just make sure its clean when heard..and,WATCH OUT FOR THE NOTES!


Write a programe to count the paticular word how may times comes in the string in c language?

this is my book this is not my book .





this -------------2times


is -------------2times


my ---------------2times


book ----------2 times


not ------------ 1 times

Write a programe to count the paticular word how may times comes in the string in c language?
Assume that every word is separated by space so check for it





now put this word in a separate array, now copy this array into a new array and read this array and compare using strcmp().
Reply:u need to break sentences into word then compare them


ie. a string into multiple strings and compare
Reply:yep. u can use strtok() to tokenize ur string with %26lt;space%26gt; as delimiter;


get the tokens in an array of strings;





for each non null word in the array


{


--each word with the rest of the words;


--{


----if u find a match


----{


-----change that match to null;


-----increment the counter;


----}


--}


--make the word u have been searching for as null.


--print the count;


}
Reply:You could step through the string as a character array and consider yourself at a new word each time you reach a space. You could also look into strtok().


(C++)how can I make a string register spaces as well as the words?

c++ question. I need to be able to store words with spaces into a variable I was think a string variable. But it cant take spaces and I need it to so what should I do?? For instance if I wanted to store


"john smith williams" all into one variable how would I do it?

(C++)how can I make a string register spaces as well as the words?
Are you talking about reading a string into the program using cin? In that case, if s is a string object, instead of:





cin %26gt;%26gt; s;





Try:





getline(cin,s);
Reply:I think you're confusing a variable name with a variable value. Names cannot contain spaces, but a string variable can contain any character, even a space.





As a parallel, consider that an int variable can be named abc, but contain the integer 100. A string variable can be named def but contain the string value "The quick brown fox jumped over the lazy dog!" Even an exclamation point is legal in a string value.





Syntactically, this would be done in one of the following ways (depending on how the compiler handles strings):





char a_char_string[ 100 ];


CString a_cstring;


...


strcpy( a_char_string, "The quick brown fox jumped over the lazy dog!" );


a_cstring = "The quick brown fox jumped over the lazy dog!";





(As a side note, notice that variable names can -- and often do -- contain underscore characters to take the place of blanks, but it's crucial that you understand the distinction between a variable's name and its contents.)
Reply:In this answer, I'm assuming that you are doing something like this:





#include %26lt;string%26gt;


#include %26lt;iostream%26gt;


int main()


{


string var1, var2;


cin %26gt;%26gt; var1%26gt;%26gt; var2;


}





The results you are seeing are a result of the way the %26gt;%26gt; operator works, try this way instead:





getline(cin, var1);





That will read a whole line, spaces and all, into var1.
Reply:take a character variable and use gets() function


e.g


char str[50];


gets(str);

strawberry

What C# codes for string manipulation should I use for this?

The running console application should be like this:





Input word/s:


Search for:





The are __ (what you've have typed from the 'search for' part)'s found.





It's like a Ctrl +f function.





When the user type a word and he/she is ask to search for any word, the new line would tell how many from what he/she have type are found when try to search for them.





Any string manipulation should I use or suggestions?





Thanks.

What C# codes for string manipulation should I use for this?
You should use "regular expressions" for programmatic searching... in any language, C#, C++, Visual Basic, Java... they all have it.





It will take a while to capture the concepts, but with a bit of effort you will suddenly have an epiphany (of sorts) and you'll want to use it for everything. I do...
Reply:Computer Tutorials, Interview Question And Answer


http://freshbloger.com/
Reply:I concur with Sam's answer, have a look at the following...





http://msdn2.microsoft.com/en-us/library...





http://msdn2.microsoft.com/en-us/library...


How do I set the number of spaces between segments of a string in C? Ex. "There is 10 spaces after %10.10s me"

Can I do that? No! I can't do:


printf("There is 10 spaces after %10.10s ");


I want to out put like this


%26gt;%26gt;There is 10 spaces after me





SO what do I do? Thaaaaaank youuuuu

How do I set the number of spaces between segments of a string in C? Ex. "There is 10 spaces after %10.10s me"
What is wrong with?


printf("There is 10 spaces after ");





or


printf("There is 10 spaces after %10.10s"," ");


C++ question, please help...?

Is there a str.charAt(number) in C++?





so that:


string a = "this is an example."


a.charAt(3) is equivalent to 's'





if there isn't, can you please tell me the alternative way of doing this in C++? Best with simple examples. Thank you very much.

C++ question, please help...?
Yes - str.at(number)





#include %26lt;string%26gt;


#include %26lt;iostream%26gt;


using namespace std;





void main()


{


string a("this is an example.");


cout %26lt;%26lt; "Char at 3: " %26lt;%26lt; a.at(3);


}





Output:





Char at 3: s





Take a look here for more :





http://www.cplusplus.com/reference/strin...
Reply:http://www.ebay.ph/viItem?ItemId=3301535...
Reply:Use the indexer ..





a[3]
Reply:there aint charat u just have at()


hey here is a small list of string functions:





append() : append a part to nther string


assign(): assigns a partial string


at(): obtains character at specified location


length(): length of string





usage


String s1;


s1="test vaue"


cout%26lt;%26lt;s1.at(3)//count starts from 0





output:


t


--------------------------------------...


all functions would have the same method for calling


String var;


var.funcnme(arglist,....);


--------------------------------------...


checktc help file if u want more data or try rading book by balguruswamy c++


Write a program that will read strings and process them until an empty string is input with the following?

im having a hard time with this right now. help





write a c program that utilizes strings and numeric conversions





1. Read strings using a function you write called getStr ().


2. Write a function named hextodecimal () that takes in (only) a string parameter representing a positive hexadecimal number and return its decimal equivalent (integer). This function returns -1 if the string provided connotes to a negative number and/or is comprised of invalid characters.


-note: you may not use any library functions in this function- you must write all code necessary to enact the coversion and return the appropriate result.


-this function must accept both upper and lower case versions of the hex character.


-You may want to write an additional function that vets any string for invalid hex character


3. If original string is invalid, output an unambiguous message to the user and prompt for another input.


4. Output the original String, followed by its decimal equivalent. Clearly label which is which.

Write a program that will read strings and process them until an empty string is input with the following?
You haven't said which part you are having trouble with? How you start is with your Hello World program, then add bits on according to the requirements of your program. The general idea is to teach you how to do conversions.

kudzu

How do i make a program that will display a selected string in c language?

ex: if i input " hello"


the output would the first the the letters like "hel"

How do i make a program that will display a selected string in c language?
#include %26lt;stdio.h%26gt;





int main()


{


char input[4];


printf("Please enter a word: ");


fgets(input, 4, stdin);


printf("\nFirst 3 characters of input: %s", input);


getchar();


return 0;


}








Enjoy!


Thursday, July 30, 2009

How to sort a string array in c++ or c?

I have an assigment to make a program which sorts names by abc order. I think it should be done in two-dimensional array but I don't know how to do it. The program code must be written in c or c++.

How to sort a string array in c++ or c?
Tamara evo resenja





#include %26lt;iostream.h%26gt;


#include %26lt;stdlib.h%26gt;


# include %26lt;string%26gt;





void selectionSort(string array[ ], const int arraySize);


int findSmallest(string array[ ], int startIndex, int endIndex);


void swap(string%26amp; first, string%26amp; second);


void print(string array[ ], const int arraySize);





int main( )


{


const int ARRAY_SIZE = 3;


string someArray[ARRAY_SIZE] = {"pera", "aca", "mika"};


selectionSort(someArray, ARRAY_SIZE);


print(someArray, ARRAY_SIZE);





system("PAUSE");


return 0;


}





void selectionSort(string array[ ], const int arraySize)


{


int smallestIndex = 0;


for(int i = 0; i %26lt; arraySize; i++)


{


smallestIndex = findSmallest(array, i, arraySize - 1);


swap(array[i], array[smallestIndex]);


}


}





int findSmallest(string array[ ], int startIndex, int endIndex)


{


int smallestIndex = startIndex;





for(int i = startIndex + 1; i %26lt;= endIndex; i++)


{


if(array[i] %26lt; array[smallestIndex])


smallestIndex = i;


}


return smallestIndex;


}





void swap(string%26amp; first, string%26amp; second)


{


string temp = first;


first = second;


second = temp;


}





void print(string array[ ], const int arraySize)


{


for(int i = 0; i %26lt; arraySize; i++)


cout %26lt;%26lt; array[i] %26lt;%26lt; endl;


}
Reply:simple:





http://www.egr.unlv.edu/~jjtse/codes/arr...


C++: How do you edit a char string from a different function that you originally declared it in?

I'm using C++.





I thought passing the char string to the function that will edit it as a reference parameter would cause the char string to be directly edited, but apparently not. Why does thie following code not work?


(Please note: You can ignore the stuff about "uniqueInteger". It's just the char str that I'm concerned about...)





How do you edit a char string from a different function that you declared it in?





#include "stdafx.h"


#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;


using namespace std;





int getToken(ifstream %26amp; myFile, char *str)


{


str = "I want to edit this in getToken(), but I declared it in main()! Help!";


return 1;


}





void main()


{


ifstream myFile("test.txt");


int uniqueInteger = 0;


char str[200];


uniqueInteger = getToken(myFile, str);


for (int i=0; i%26lt;10; i++)


{


cout %26lt;%26lt; str;


}


cout %26lt;%26lt; "\nType was " %26lt;%26lt; uniqueInteger %26lt;%26lt;"\n";





myFile.close();


system("PAUSE");


}

C++: How do you edit a char string from a different function that you originally declared it in?
//#include "stdafx.h"


#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;


using namespace std;





int getToken(ifstream %26amp; myFile, char *str) {


cout%26lt;%26lt;"function call "%26lt;%26lt;endl;


char alfa[]="final1";


int i=0;


while((*str!='\0')%26amp;%26amp;(i%26lt;6)){


*str=alfa[i];


++str;


i++;


}





return 1;


}





int main(){


ifstream myFile("test.txt");


int uniqueInteger = 0;


//char *str = new char[200];


char str[] = "inicio";


cout%26lt;%26lt;"inicial main "%26lt;%26lt;str%26lt;%26lt;endl;


uniqueInteger = getToken(myFile, str);


for (int i=0; i%26lt;10; i++){


cout %26lt;%26lt;" cada linea en main "%26lt;%26lt;i%26lt;%26lt;"-%26gt;"%26lt;%26lt;str%26lt;%26lt;endl;


}


cout %26lt;%26lt; "\nType was " %26lt;%26lt; uniqueInteger %26lt;%26lt;"\n";





myFile.close();


system("PAUSE");


return 0;


}


i think this is you want be more specific. bye


What are the string sizes for the B.C. Rich SOB guitar?

http://www.musiciansfriend.com/product/B...


Thats it. Can anyone tell me the string size for it?

What are the string sizes for the B.C. Rich SOB guitar?
I myself have the original Beast. Heaviest damn guitar I've ever played. The SOB is alot lighter.





As far as strings go. If I remember correctly they come factory fitted with 9-42's. You can go pretty high on the gauges for BC Rich's.





Some BC Rich's come with speed loader strings and you need to get the right scale string but I don't think this one has those.





I had mine fitted with GHS Zakk Wylde Boomers. They come in 10-13-17-36-52-60 and 11-14-18-36-52-70. I suggest going with the 11-70's but I warn you it will destroy your fingers.


Gives it an even heavier sounds. You'll want to get the first setup with those done by a good guitar tech.

garland flower

C++ Code in String?

How can i calculate the number of WORDS in my string.


(note:string was filled by cin.getline command),ie.





string mystr;


cout %26lt;%26lt; "Enter the text: ";


getline(cin,mystr,'\n');





NOW,who can i calculate the number of words of my text...


please help i need this code

C++ Code in String?
hay, thats an easy one, it put the answer on my site.





www.EvilMark.co.uk





you can find it under the Programming Q%26amp;A link.
Reply:string mystr;


int i = 0;


int words = 1;


cout %26lt;%26lt; "Enter the text: ";


getline(cin,mystr,'\n');





for(i = input.find(" ", 0); i != string::npos; i = input.find(" ", i))


{


words++;


i++;


}


cout%26lt;%26lt;words;





//////////////////////////////////////... will count all the spaces plus one, and that should be all the words


How do you concatenate a single char onto a string in C?

Given: string s, char c as in:





char s[ 256 ]; //256 is assumed, it can be anything.


char c;





Way 1.


=====





char temp[ 2 ];


temp[ 0 ] = c;


temp[ 1 ] = '\0';


strcat( s, temp );





Way 2.


=====





int iOriginalLength = strlen( s );


s[ iOriginalLength ] = c;


s[ iOriginalLength + 1 ] = '\0';





Way 3


=====


#include %26lt;string%26gt;


using namespace std;


string sNew = s;


sNew += c;


strcpy( s, sNew.c_str() );

How do you concatenate a single char onto a string in C?
Strings in C


Follow these fast links:





strlen()


strcpy()


strncpy()


strcat()


strncat()


strcmp()


strncmp()


Miscellaneous Notes


This discussion of string handling in C presumes that the following compiler directive is used.





#include %26lt;string.h%26gt;





On Linux, this file is located in /usr/include. Only the basic functions will be discussed here, so you may want to investigate string.h.





In C, a string is stored as a null-terminated char array. This means that after the last truly usable char there is a null, hex 00, which is represented in C by '\0'. The subscripts used for the array start with zero (0). The following line declares a char array called str. C provides fifteen consecutive bytes of memory. N.B. Only the first fourteen bytes are usable for character storage, because one must be used for the string-terminating null.





char str[15];





The following is a representation of what would be in RAM, if the string "Hello, world!" is stored in this array.





Characters: H e l l o , w o r l d !


Hex values: 48 65 6C 6C 6F 2C 20 77 6F 71 6C 64 21 00


Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14





The name of the array is treated as a pointer to the array. The subscript serves as the offset into the array, i.e., the number of bytes from the starting memory location of the array. Thus, both of the following will save the address of the 0th character in the pointer variable ptr.





ptr = str;


ptr = %26amp;str[0];





Back to Top





strlen()


Syntax: len = strlen(ptr);


where len is an integer and


ptr is a pointer to char





strlen() returns the length of a string, excluding the null. The following code will result in len having the value 13.





int len;


char str[15];





strcpy(str, "Hello, world!");


len = strlen(str);





Back to Top





strcpy()


Syntax: strcpy(ptr1, ptr2);


where ptr1 and ptr2 are pointers to char





strcpy() is used to copy a null-terminated string into a variable. Given the following declarations, several things are possible.





char S[25];


char D[25];





Putting text into a string:





strcpy(S, "This is String 1.");





Copying a whole string from S to D:





strcpy(D, S);





Copying the tail end of string S to D:





strcpy(D, %26amp;S[8]);





N.B. If you fail to ensure that the source string is null-terminated, very strange and sometimes very ugly things may result.





Back to Top





strncpy()


Syntax: strncpy(ptr1, ptr2, n);


where n is an integer and


ptr1 and ptr2 are pointers to char





strncpy() is used to copy a portion of a possibly null-terminated string into a variable. Care must be taken because the '\0' is put at the end of destination string only if it is within the part of the string being copied. Given the following declarations, several things are possible.





char S[25];


char D[25];





Assume that the following statement has been executed before each of the remaining code fragments.





Putting text into the source string:





strcpy(S, "This is String 1.");





Copying four characters from the beginning of S to D and placing a null at the end:





strncpy(D, S, 4);


D[4] = '\0';





Copying two characters from the middle of string S to D:





strncpy(D, %26amp;S[5], 2);


D[2] = '\0';





Copying the tail end of string S to D:





strncpy(D, %26amp;S[8], 15);





which produces the same result as strcpy(D, %26amp;S[8]);





Back to Top





strcat()


Syntax: strcat(ptr1, ptr2);


where ptr1 and ptr2 are pointers to char





strcat() is used to concatenate a null-terminated string to end of another string variable. This is equivalent to pasting one string onto the end of another, overwriting the null terminator. There is only one common use for strcat().





char S[25] = "world!";


char D[25] = "Hello, ";





Concatenating the whole string S onto D:





strcat(D, S);





N.B. If you fail to ensure that the source string is null-terminated, very strange and sometimes very ugly things may result.





Back to Top





strncat()


Syntax: strncat(ptr1, ptr2, n);


where n is an integer and


ptr1 and ptr2 are pointers to char





strncat() is used to concatenate a portion of a possibly null-terminated string onto the end of another string variable. Care must be taken because some earlier implementations of C do not append the '\0' at the end of destination string. Given the following declarations, several things are possible, but only one is commonly used.





char S[25] = "world!";


char D[25] = "Hello, ";





Concatenating five characters from the beginning of S onto the end of D and placing a null at the end:





strncat(D, S, 5);


strncat(D, S, strlen(S) -1);





Both would result in D containing "Hello, world".


N.B. If you fail to ensure that the source string is null-terminated, very strange and sometimes very ugly things may result.





Back to Top





strcmp()


Syntax: diff = strcmp(ptr1, ptr2);


where diff is an integer and


ptr1 and ptr2 are pointers to char





strcmp() is used to compare two strings. The strings are compared character by character starting at the characters pointed at by the two pointers. If the strings are identical, the integer value zero (0) is returned. As soon as a difference is found, the comparison is halted and if the ASCII value at the point of difference in the first string is less than that in the second (e.g. 'a' 0x61 vs. 'e' 0x65) a negative value is returned; otherwise, a positive value is returned. Examine the following examples.





char s1[25] = "pat";


char s2[25] = "pet";





diff will have a negative value after the following statement is executed.








diff = strcmp(s1, s2);





diff will have a positive value after the following statement is executed.








diff = strcmp(s2, s1);





diff will have a value of zero (0) after the execution of the following statement, which compares s1 with itself.








diff = strcmp(s1, s1);





Back to Top





strncmp()


Syntax: diff = strncmp(ptr1, ptr2, n);


where diff and n are integers


ptr1 and ptr2 are pointers to char





strncmp() is used to compare the first n characters of two strings. The strings are compared character by character starting at the characters pointed at by the two pointers. If the first n strings are identical, the integer value zero (0) is returned. As soon as a difference is found, the comparison is halted and if the ASCII value at the point of difference in the first string is less than that in the second (e.g. 'a' 0x61 vs. 'e' 0x65) a negative value is returned; otherwise, a positive value is returned. Examine the following examples.





char s1[25] = "pat";


char s2[25] = "pet";





diff will have a negative value after the following statement is executed.








diff = strncmp(s1, s2, 2);





diff will have a positive value after the following statement is executed.








diff = strncmp(s2, s1, 3);





diff will have a value of zero (0) after the following statement.








diff = strncmp(s1, s2, 1);





Back to Top





Miscellaneous Notes


Single characters can be replaced in a string. Given the following declarations, several things are possible.





char str[25] = "cot";


char ch = 'u';


char D[25] = "pat";





Replacing a single character using a char variable:





D[1] = ch;





This would result in D containing "put".





Replacing a single character using a char literal:





D[1] = 'e';





This would result in D containing "pet".





Replacing a single character using a single character from a string variable:





D[1] = str[1];





This would result in D containing "pot".





Back to Top
Reply:Alternatively, way easier:





- put the character into a new string, and use strcat





or





- If you are absolutely CERTAIN that sizeof(string) %26gt; strlen(string), do:





string[strlen(string)] = char; /* copy the string as last */


string[strlen(string)] = '\0'; /* Terminate with NULL */





explanation: since we count offsets from 0 in C, string[strlen(string)] points to the null at the end of the string. Replace it with the char in question. Then, strlen(string) points at the NEW end of the string - make sure there's a null there.





BE CAREFUL. If the string doesnt have enough memory, you risk a buffer overflow! This could lead to miscellaneous weird effects, culminating in program crash, or even code injection.





Hope This Helps,





J