Issue With Modifying Value in Character in Char Array

I'm currently working my way through Ivor Horton's book on Visual C++ 2012. I'm working on the third exercise at the end of chapter 4. The exercise is to change every other letter to uppercase. It keeps throwing an access violation. Any thoughts would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  //ChangeToUpper.cpp
//Take string, change every other letter to capital
#include <iostream>
using std::cout;
using std::endl;

int main()
{
    char* str = "Now is the time for all good men to come to the aid of their country.";
    int count = 0;
    int length = strlen(str);

    for(int i = 0; i < length; i++)
    {
        if(str[i] != ' ' && str[i] % 2 == 0)
            str[i] = str[i] - 32; //Error occurs here,
    }

    cout << endl
         << str
         << endl;

    return 0;


 
First-chance exception at 0x00AF7BDF in ChangeToUpper.exe: 0xC0000005: Access violation writing location 0x00AFCC78.
Last edited on
The debugger points to this line as the issue:
 
str[i] = str[i] - 32;
str can't be modified as you have it created here as a string literal

char* str vs char str[] explanation here
http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string


You may need to check how you're choosing which characters to change - this is what I get after changing str to be char str[].

.ow is THe Time FoR aLL gooD meN To come To THe aiD oF THeiR couNTRy



Edit: or you could use <string> instead of a character array if the assignment allows.
Last edited on
Well, my first reply seems to have gotten lost.

Thank you for the help, wildblue. I haven't finished perusing the page you suggested, but pretty much the first paragraph resolved my issue with the access violation. Now to puzzle out my logic problem. That should be straight-forward.

BTW, I'm using a char array because that's what the exercise asked for. I'm only four chapters in and he hasn't covered strings yet.
Topic archived. No new replies allowed.