char of array and string

i try to print user input , only even and odd words.
input :
hacker
rank

output :
hce akr
rn ak

but seems i misunderstood about string and array of char in c++

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
38
39
40
41
42
  


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int i;
    int s;
    cin>>i; //for how many input
    
    
   string a; //not sure, can i?
    string odd;
    string b;
    for(int j=0;j<i;++j)
{
    cin>>a;
    for(int k=0;k<a.length();k++)
    {   if(k%2==0)
    b+=a[k];
     else
     odd+=a[k];
    }
    b+=" ";
    odd+=" ";
}  
    cout>>b>>"\n";
    cout>>odd>>"\n";
    return 0;
    
    
}



this is so wrong :(
havent learn stl yet
Last edited on
char arrays are really a relic from C, but c++ used them for many years as well back when there were a number of nonstandard and poor performing string classes. Since the STL, std::string has been the way to go.

You can iterate either one though.
for a std::string you can use [] to pick off letters and its length to do this task.
for a char array, you can use[] and strlen() to do the task.
its almost the same code, really, just different words.

I think what you have is close. Trying to spot the issue.

line 35 and 36 have the wrong >> operator for cout. Its cout << stuff

with that fix it appears to work, but I didnt test it much? What are you asking?
you are giving even and odd *letters* not *words*.
to do even and odd words, you would do this
vector<string> s(some max size);
for(...)
cin >> s[index]; //or, cin tmp, s.push-back if you prefer.

then
for(index = 0; index < s.size(); index += 2) //evens, similar for odds
cout << s[index] << endl;

or in a nutshell, make a container of strings and take every other one.
Last edited 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
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>

using namespace std;


int main() {
	/* Enter your code here. Read input from STDIN. Print output to STDOUT */
	


	string a = "hacker";
	string b = "rank";
	string c;
	string d;
	int j = a.length();
	
	for (int i = 0; i < j; i += 2) {
		c += a[i];
		if (i + 2 >= j && i % 2 == 0) {
			c += ' ';
			i = -1;
		}
	}

	j = b.length();

	for (int i = 0; i < j; i += 2) {
		d += a[i];
		if (i + 2 >= j && i % 2 == 0) {
			d += ' ';
			i = -1;
		}
	}
	
	cout << c << "\n";
	cout << d << "\n";

	cin.get();
	return 0;

}
Topic archived. No new replies allowed.