quick string question

Started by
10 comments, last by Stashi 22 years, 5 months ago
i want to declare a string variable with an unknown length (this string will be entered in by the user when running program) and basically im trying to make a function that reverses the entire string. basically i just need to know how to change a certain index in the string array to a different character.. i've tried this..
    
char *str;
char tmp;
int length;
cin >> str;
length = strlen(str);
for (int x = length-1; x=0; x--) {
    tmp = str[x-1];
    str[x-1] = str[x];
    str[x] = tmp;
}
    
which obviously doesnt work and i know to change the characters i need to make use of some "str" function but i dont know which one or how to...any help? Edited by - Stashi on November 17, 2001 10:41:28 PM
Advertisement
You can''t input data into a "char *" that doesn''t point to appropriate data. You can try using the STL strings or a constant sized buffer. Also the second ''argument'' for your for loop won''t work (try x>1).

[Resist Windows XP''s Invasive Production Activation Technology!]
    char str[1024]; // sorry you eighter use a buffer or new your string before trying to store anything there.  char tmp;  int length;  cin >> str;  length = strlen(str);  for (int x = length-1,y = 0; x>y; x--,y++) {    tmp = str[y];    str[y] = str[x];    str[x] = tmp;  }  cout << str;  return 0;  

That Anon was me
that doesn''t work
are you sure? I complied that, and it does reverse the string, here is the whole thing:

  #include <stdio.h>#include <string.h>#include <stdlib.h>#include <stream.h>int main(){  char str[1024];  char tmp;  int length;  cin >> str;  length = strlen(str);  for (int x = length-1,y = 0; x>y; x--,y++) {    tmp = str[y];    str[y] = str[x];    str[x] = tmp;  }  cout << str;  return 0;}  

Alternatively you can use this..

char *buffer; //your primary buffer (string)

a) put some string in it

void getstring(char *string)
{
if (string == NULL) string=""; //just checking

buffer = new char[strlen(string)+1]; //set new length
strcpy(buffer, string); //copy string
}


b) to replace a character in string->

void replace(char ch1, char ch2) //ch2 is replacement char
{
char* temp=strchr(buffer, char1);
if (temp != NULL) *temp=char2;
}

Thats all......

(always anonymous)





That sounds suspiciously like homework to me...
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

sorry..some corections.

actually char1 & char2 in b) is ch1 & ch2...

(always anonymous)
to reverse a string->

length = strlen(str); length--;

for (int x=0; x<(length)/2; x++)
{
str[x]=str[length-x];
str[length-x]=str[x];
}

(anonymous poster)

This topic is closed to new replies.

Advertisement