Jump to content
  • Advertisement
Sign in to follow this  
MTM

I have a problem with char*

This topic is 2858 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,
I have a problem with char*.

1)Please tell me why this code is wrong?

#include <iostream>
using namespace std;

void main()
{
char* s = "hello";
s[1] = 'n';
cout << s;
}
2)How can I change an index of my char*?
(In fact I want to delete some part of my char* for example I want to change "FirstName:Jack" to "Jack")

for now!

Share this post


Link to post
Share on other sites
Advertisement
<insert usual disclaimer about using std::string rather than char*>

1) your code is wrong because you make s point to a constant literal string which can not be modified (s should have type const char* in your example)
If you want to initialize a char array from a literal, use:

char s[] = "hello";


You can then modify that array.

2) there are many ways to do that. unless you use std::string instead (which offers high level string manipulation functions), it boils down to manual array manipulation.

An *example* (I encourage you to use std::string instead)


char s[] = "FirstName:Jack";
for (int i = 0 ; i < 5 ; i++)
s = s[i+10]; // because 'J' is at index 10

Share this post


Link to post
Share on other sites
Since the previous poster provided actual helpful relevant posts, heres my help:

It's wrong because it uses char*. Since you are obviously using C++, char* is basically considered evil as a string. Use std::string instead.

Share this post


Link to post
Share on other sites
Q2)

You can create suffix substrings using pointer arithmethic:

#include <iostream>
#include <algorithm>

int main()
{
const char *string = "FirstName:Jack";
std::cout << "Full string: " << string << '\n';
const char *end = string + std::strlen(string);
const char *substring = std::find(string, end, ':');

if(substring == end)
{
std::cout << "Failed to find \':\' in string\n";
}
else
{
std::cout << "Sub string: " << (substring + 1) << '\n';
}
}


But to echo Steve132, std::string is almost always a superior solution.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!