Counting the chars?

Hello,

I tried to make a code that turns the letters of a word, in a compact way (so not with extra functions). Dere is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <vector>

using namespace std;

main() {
char hoi[500];
int i; // i becomes the size of vector kip


cout << "Hello!" << endl << "type something: ";
cin.getline(hoi,500);

vector<char> kip (hoi, hoi + sizeof(hoi) / sizeof(int) ); // standard coding


  for (i=kip.size(); i >= 0; i--) // as long as i isn't less than 0, the vector is printed. 
    cout << kip[i];
cin.get();
return 0;
}


and what I get is this:

C:\CPPs\hoi>hoi
Hello!
type something: damn it
¶ ☻ å*@ ↕²t Aí@ ↕²╚Zz■░ ↕²< AíÇ @╪☼ ↕²╠ ↕²¿ → @;H z Z ¶N≡ A{¼ ↕■░ A¥( å1É ☻ ↕²á
@╖ⁿ ti nmad


So what happens is that empty chars are getting stored in the vector, and the vector prints them as strange chars.

Can someone help me?

Jyy.
You can use strlen from <cstring> to give you the length up to (but not including) the null, which marks the end. andm you shouldn't be dividing by sizeof(int), hoi + strlen(hoi) will point to the last letter.
Last edited on
Thanks! for the one's who want to know, this is my code now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <vector>

using namespace std;

main() {
char hoi[500];
int i; // i becomes the size of vector kip


cout << "Hello!" << endl << "type something: ";
cin.getline(hoi,500);

vector<char> kip (hoi, hoi + strlen(hoi)); // standard coding


  for (i=kip.size()-1; i >= 0; i--) // as long as i isn't less than 0, the vector is printed. 
    cout << kip[i];
cin.get();
return 0;
}
Why use "char hoi[500];" rather than "std::string hoi;"?
Topic archived. No new replies allowed.