reversed string: string space problem

hi,

how can i output users input sentences - with spaces
ive tried with strings, but no luck, but i also want to know how to do it with chars:

char example (Problem: cant output after space):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

char* Reverse(char* s1, int length1)   
{                                           
	for ( int cnt1 = 0, cnt2 = (length1 - 1); cnt2 > (length1 - 1)/2 ; 
              cnt1++, cnt2--)  
	{
		/*if( s1[cnt1] == ' ' || s1[cnt2] == ' ' ) //
		  {                                        //this is how i 
			  cnt1++; cnt2--;                  //tried to solve it
		  }*/                                      // =>but doesnt 
                                                           // do anything...
		int temp = s1[cnt1];    
		s1[cnt1] = s1[cnt2];     
		s1[cnt2] = temp;        
	}
	return s1;
}

int main()
{
	char *s = new char[256];           
	cout << "Enter a string: ";
	cin >> s;         

	cout << "Reversed string = ";
	int length = strlen(s);
	Reverse(s, length);  

	for(int i = 0; i < length; ++i)
              cout << s[i];
	cout << endl;

	delete[] s;
	s = 0;
}


string examle: (Problem: in this example, the strings arent reversed)
(here ive just putted something fast together, because i dont have a clue how to do it :))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
using namespace std;

void Reverse(string s1)   
{
int length = s1.size();
for ( int cnt1 = 0, cnt2 = (length - 1); cnt2 > (length - 1)/2 ; cnt1++, cnt2--)
{
string subs1 = s1.substr( cnt1, 1 );
string subs2 = s1.substr( cnt2, 1 );

string temp = subs1;    
subs1 = subs2;     
subs2 = temp; 
}
}

int main()
{
	string s = "";        
	cout << "Enter a string: ";
	getline(cin, s);         

	cout << "Reversed string = ";
	Reverse(s);  

    cout << s << endl;
}


ty in advance!
Last edited on
all im asking is:

- how can you navigate through/manipulate with (every) characters in a string
- how can you make spaces with chars (c-strings)
std::string::operator[]()
ive tried that already but no luck:

1
2
3
char tmp = s1[cnt1];
s1[cnt1] = s1[cnt2];
s1[cnt2] = temp;


everything is the same...it wont reverse
Last edited on
Okay, I just read your first post completely and understand your second question. The spaces thing is a problem with std::cin. If you need spaces, just don't use std::cin to input. Actually, never use std::cin (except in combination with std::getline(), that is).

Reverse() actually does reverse the string. The problem is that it reverses the wrong string. You're passing a copy of the string. The quickest way to change it is by placing an & after string and before s1 on line 5.
You should be using this:
http://cplusplus.com/reference/algorithm/reverse/

Helios is wrong. The reverse function is reversing the characters in the temporary strings returned by std::string::substr. The s1 string is not being modified at all by the function. Even if it were passed by reference it would make no difference.

1
2
3
4
5
6
7
8
9
10
11
int main()
{
    string s = "";        
    cout << "Enter a string: ";
    getline(cin, s);         

    cout << "Reversed string = ";
    std::reverse(s.begin(), s.end());

    cout << s << endl;
}


If you still want to code your own reverse function, don't bother with all of the temporary strings in your functions. Read the example code on the website I showed you and do it that way using iterators or simple array positions. You can modify the string in place. You just need a temporary character variable while you are doing each swap or use std::swap. Then again, I don't see the point of rewriting the std::reverse function at all here.
Last edited on
well the point of rewriting is that it is for learning puposes

and helios was right, but your post was helpful too - because ive learned sth from both of you :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
/*#include <algorithm>*/  // 3. possibility
using namespace std;

void Reverse(string& s1)
{
int length = s1.size();
for ( int cnt1 = 0, cnt2 = (length - 1); cnt2 > (length - 1)/2 ; cnt1++, cnt2--)
{
    char temp = s1[cnt1];
    s1[cnt1] = s1[cnt2];                   // 1. possibility
    s1[cnt2] = temp;

    /*swap(s1[cnt1], s1[cnt2]);*/   // 2. possibility 
}
}

int main()
{
	string s = "";        
	cout << "Enter a string: ";
	getline(cin, s);         

	cout << "Reversed string = ";
	Reverse(s);  
	/*reverse(s.begin(), s.end());*/ // 3. possibility 

    cout << s << endl;
}


only one more question left though - with chars, how can you manipuate with spaces?
The spaces thing is a problem with std::cin. If you need spaces, just don't use std::cin to input. Actually, never use std::cin (except in combination with std::getline(), that is).
ive tried that already (getline(cin, s);), but i get this error:

- error C3861: 'getline': identifier not found

ive read that you might have to write your own cin or sth for char, if you want to use spaces...
You didn't #include <string>.
i did that too, and then i get:

- error C2780: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem)' : expects 3 arguments - 2 provided

- error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'std::basic_string<_Elem,_Traits,_Alloc> &' from 'char *'


for the first one i tried getline(cin, s, ' '); but nothing....
How are you calling it? Post the call itself and the declaration of its parameters (not std::cin, of course).
thats it ->

getline(cin, s, ' ');

if i unrestood you right...

or you ment function :
Reverse(s, length);
Last edited on
s is this char *s = new char[256]; , right?
std::getline() takes a reference to an std::string as its second parameter. The third parameter is normally not needed.
What you'll do after getline()ing is allocate a C string with new char[/*name of the string*/.size()+1]
Then simply strcpy(/*name of the allocated C string*/,/*name of the string*/.c_str())
strcpy() is defined in <cstring>.
Last edited on
well first of all, now i realised that you cant read spaces with char, rather, you need a C STRING EQUIVALENT - which makes things a bit different of course

i did what you said, but it still wont read from the white space on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

char* Reverse(char* s1, int length1)   
{                                           
	for ( int cnt1 = 0, cnt2 = (length1 - 1); cnt2 > (length1 - 1)/2 ; cnt1++, cnt2--)  
	{
		int temp = s1[cnt1];    
		s1[cnt1] = s1[cnt2];     
		s1[cnt2] = temp;        
	}
	return s1;
}

int main()
{
	string str = "";
	cout << "Enter a string: ";
	cin >> str;     

	char *cstr = new char[str.size()+1];
	strcpy (cstr, str.c_str());

	cout << "Reversed string = ";
	int length = strlen(cstr);
	Reverse(cstr, length); 
 
	cout << cstr << endl;

	delete[] cstr;
	cstr = 0;
}
Line 21: No. You use GETLINE().
oops my mistake, i forgot to change it, now it works

ty for all your help!
The only things that you will learn by attempting to rewrite the std library are bad habits. For one thing you are still reverting to the use of dynamically allocated character arrays and making extra, unnecessary copies of the input string. You should be using only the std::string that encapulates the original string that was received from the input stream. Moreover, if you really wanted to understand how the reverse function works you'd be attempting to use iterators rather than passing the character array. The reason I say that this is a bad habit is that I have seen numerous instances of professional programmers rewriting these functions out of ignorance because they never took the time to go through the examples and actually learn what all is available within the std library. If you really want to develop good habits, read every single example (on this website) of every single std algorithm and container class and write sample programs that use those algorithms that are provided for you. In fact this website provides some sample programs that are very easy to compile and debug. This would be a much better learning approach then attempting to rewrite those library functions and containers. Most of the rewrites that I have seen attempted on this site are like poor karaoke performances.
you know what, i agree with you completely and ill listen to your advice, but if i make such programs BUT not use them in real programs, just for learning purposes, i think ill be ok...
Topic archived. No new replies allowed.