help with strings/char

Hi, I have been asked to edit this code into working order, then edit it. I just cant seem to get it to compile, I'm not asking for a solution, just if you could hint at what's wrong with the below code!

many thanks in advanced.

EDIT: I've noticed i need to include <string>!

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>
using namespace std;

int main() {

     char word = "fire";
     word[0] = 'h';
     cout << word << endl;
     word[3] = 'd';
     cout << word << endl;
     word[4] = '\n';
     cout << word << endl;

     string str1("Now is");
     string str2 = " the winter";
     cout << str1 << str2 << " of our discontent..." << endl;
     string str3 = str1 + str2 + " of our discontent";
     cout << str3 << endl;

return 0;
}

Last edited on
I just cant seem to get it to compile

This generally means that there are some errors or something, could you post those?

The things that jump out at me are:
-word is a single character, but you try assigning a string literal to it.
-"fire" is only four characters long, so what do you think word[4] (assuming that you fixed the above) is accessing (remember that c-strings are null terminated)?
Last edited on
On line 7, you're declaring word to be a single character, when I think you want it to be an array of characters:
char word[] = "fire";
The next problem is going to be, "fire" is actually 5 characters long:
word[0] = 'f'
word[1] = 'i'
word[2] = 'r'
word[3] = 'e'
word[4] = '\0'

That last guy is what is known as a "null terminator". For C-style strings (the ones that use arrays of characters) the null terminator is how the end of the string is detected. You can't see it, but under the covers the compiler adds this terminator to string literals like "fire". However, on line 12 you're overwriting the null terminator with a newline character. So, when you go to print this, whatever is printing the stream is going to print the word, then a newline, and then it is going to keep interpreting the memory on after that until it runs into something that looks like a null terminator.

EDIT: Looks like Danny beat me to the post!
Last edited on
thanks guys, i obviously wasnt listening when we covered char! makes sense now!
Topic archived. No new replies allowed.