Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C++
string title = "I like to code."
char arr[title.size() + 1];
strcpy(arr, title.c_str());
int i = 0;
while(arr[1][i] != 0){
	if(arr[1][i] == ' '){
		arr[1][i] = '-';
	};
	i++;
};
string name(arr);
return name;


This is the code that I have mashed together. As you can see, I am converting a string into an array, going through the array char by char, replacing spaces with dashes as I go along, then converting the end result back into a string. The problem is that the compiler throws back 'error: invalid types for array subscript' for the 'while' statement and the two lines after it. How can I fix this? Thanks, all!

What I have tried:

I have tried using the std::replace template from #include <algorithm>, but to no avail.
Posted
Updated 19-Aug-16 7:05am

1 solution

Try to replace all arr[1][i] with arr[i] to make the compiler happy.

To track other bugs:
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.
 
Share this answer
 
Comments
Anti-Antidote 19-Aug-16 13:53pm    
THANK YOU SO MUCH! I've been trying to fix this for the past five hours, and it's been driving me crazy! Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900