Efficient C++ String Manipulation: Tips and Tricks from Experts

  • C/C++
  • Thread starter yungman
  • Start date
  • Tags
    C++ Strings
In summary: St1;The name stored in memory is: TestThe name stored in memory is: TesterThe name stored in memory is: Tester123
  • #1
yungman
5,718
241
Question

Is there anyway to copy the content of a string into a C-String and make the length of C-String the right length of the string? This is the program I try to do, of cause this is NOT working. I don't know of any way to do this. I just want to run by you experts whether it's possible that I have not learn in the book. This is what I want to do, I want to input a name into ST1, I use a string pointer ptr to allocate memory of length of St1. Then store the content of St1 into the allocated memory and then finally print the content of the memory.
C++:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
    string St1;
    cout << " Enter a name: "; getline(cin, St1);
    int length = St1.length();
    string* ptr;
    ptr = new string[length];
    *ptr = St1;
    cout << " The name stored in memory is: " << *ptr << "\n\n";
    delete[] ptr;
    return 0;
}

Book never teach this, I just wonder whether I can do it or not. Point is I want to allocate just enough memory for the length of the string from the getline(cin, St1).

Thanks
 
Technology news on Phys.org
  • #2
What do you mean that it is not working? It seems to work when I run it. I tried printing out the variable length. When I entered 'Test', then length=4. When I entered 'Tester', the length=6. When I entered 'Tester123', then length=9. What is it you want it to do that it is not doing?
 
  • Like
Likes yungman
  • #3
phyzguy said:
What do you mean that it is not working? It seems to work when I run it. I tried printing out the variable length. When I entered 'Test', then length=4. When I entered 'Tester', the length=6. When I entered 'Tester123', then length=9. What is it you want it to do that it is not doing?
I know, It compile and everything works the first time. But I cannot even build solution without having error. I don't know why.
Error message..jpg


I have so much trouble with VS I just assume I did something wrong.

Thanks
 
  • #4
I can't help you with VS. I just entered the program you showed in a text editor on a Unix machine, compiled it with g++, and it ran. Personally, I'd advise dumping Windows and installing Linux on your machine.
 
  • Like
Likes sbrothy
  • #5
phyzguy said:
I can't help you with VS. I just entered the program you showed in a text editor on a Unix machine, compiled it with g++, and it ran. Personally, I'd advise dumping Windows and installing Linux on your machine.
Thanks for your reply. I really don't know enough what do you mean about Windows or Linux. All I know is VS is really really...I really don't want to say how I feel! It is just so inconsistent. This is not the first time, not the second time. You sneeze, it changed. I used so many other programs in simulation and pcb layout and all that. Never have I once see a program so.....I don't want to say anymore!
 
  • #6
yungman said:
Is there anyway to copy the content of a string into a C-String and make the length of C-String the right length of the string?
Your program doesn't have any C-strings in it.
Also, the line below doesn't do what you seem to think it's doing.
C++:
ptr = new string[length];
What it's actually doing is creating an array of Standard Template Library string objects, where the array has as many elements as the length of the original string that was entered.
To copy the contents of an STL string to a C-string (i.e., a null-terminated array of type char) you can use a member of the string template class -- c-str() -- see https://docs.microsoft.com/en-us/cpp/standard-library/basic-string-class?view=vs-2019#c_str.

C++:
string str1 ( "Hello world" );
// Converting a string to a C-style string
const char *c_str1 = str1.c_str ( );
yungman said:
I have so much trouble with VS I just assume I did something wrong.
Probably a reasonable assumption.
phyzguy said:
I can't help you with VS. I just entered the program you showed in a text editor on a Unix machine, compiled it with g++, and it ran.
It compiles and runs in VS on a Windows machine as well

yungman said:
I know, It compile and everything works the first time. But I cannot even build solution without having error. I don't know why.
Why do you mean "everything works the first time"?
The error you see is a Link error. Do a search on LNK1104.
 
  • Like
Likes sbrothy and Vanadium 50
  • #7
Mark44 said:
Your program doesn't have any C-strings in it.
Also, the line below doesn't do what you seem to think it's doing.
C++:
ptr = new string[length];
What it's actually doing is creating an array of Standard Template Library string objects, where the array has as many elements as the length of the original string that was entered.
To copy the contents of an STL string to a C-string (i.e., a null-terminated array of type char) you can use a member of the string template class -- c-str() -- see https://docs.microsoft.com/en-us/cpp/standard-library/basic-string-class?view=vs-2019#c_str.

C++:
string str1 ( "Hello world" );
// Converting a string to a C-style string
const char *c_str1 = str1.c_str ( );
Probably a reasonable assumption.
It compiles and runs in VS on a Windows machine as well

Why do you mean "everything works the first time"?
The error you see is a Link error. Do a search on LNK1104.
Thanks for the reply.

When I said it worked the first time, I meant it works, I put in my name and it repeat my name...both first and last name. I repeat over and over and it was working. I never learn this in the book, I have an occasion I need to do this, so I try in a much simpler program like this. I was going to post and ask whether it is "legal" to do it like this even though it works. But then it started failing.

It's funny, I exhausted everything. You see the error window said "cannot open Copy string into C string"?

I finally just copy the exact code, created new project in repos and it compile and ran one time through! It is a WORKING program. I did rebuild solution over and over. I closed the program and tried again. Finally I had to copy and create a new project and it works without changing anything.

I really don't know what I did to offend the VS! Now I have both program opened, one failed and one working...The exact same code.About C-String, I thought it's just char array that you can do char Ar[]="this is a test". It's nothing more than a char array. I never really understand the difference between C-String and char array.

Thanks
 
  • #8
yungman said:
I finally just copy the exact code, created new project in repos and it compile and ran one time through! It is a WORKING program. I did rebuild solution over and over. I closed the program and tried again. Finally I had to copy and create a new project and it works without changing anything.

I really don't know what I did to offend the VS! Now I have both program opened, one failed and one working...The exact same code.
The warning and error you show in post #3 is likely due to a permissions issue. After you built your program, when you click Rebuild Solution, what happens is that VS deletes all of the intermediate files and .obj files and the .exe file (but not your .cpp and .h files), and then recompiles your code and links in any library code your program uses. I believe the warning and error occurred because VS does not have permission to delete the old executable. You can probably get around this by starting VS as an administrator. Then it shouldn't have any problem rebuilding.
yungman said:
About C-String, I thought it's just char array that you can do char Ar[]="this is a test". It's nothing more than a char array. I never really understand the difference between C-String and char array.
This was probably covered in the Gaddis book.
A C-string is null-terminated array of characters. A char array is just an array of characters.
C++:
char str1[] = {'C', 'a', 't'};
char str2[] = "Cat";
str1 is a character array -- no null character at the end. str2 is a C-string -- it's null terminated.
 
  • Like
Likes yungman
  • #9
Thanks Mark. Now this is a really stupid question. How do I run as an administrator? I never set up any of my laptop for administrator or anything, this is the only mode I ever run.

So the null char at the end is the only thing that separates str1 and str2?

Thanks
 
  • #10
I have been looking at the difference between the two projects comparing all the taps, these are the difference I found:

This is one difference between the one with compile error(left) vs one that works.
Project difference.jpg


The Project option menu is different. This is the one that works.
Project work.jpg


This is the one that gives error:
Project error.jpg
These are the difference I can see between the two. I am sure I did not change any setting on the one that was working before and not working later.

Thanks
 
  • #11
yungman said:
I have been looking at the difference between the two projects comparing all the taps, these are the difference I found:

This is one difference between the one with compile error(left) vs one that works.
"comparing all the taps" -- ? Do you mean "tops"?

The program that doesn't work isn't configured correctly. The one that works is configured to build in debug mode for the x86 architecture (i.e., 32-bit Windows). The one that doesn't work doesn't seem to be configured at all. I don't know how that would have happened.
I'm running an older version VS, but I'm pretty sure this will work in yours - on the Build menu, click Configuration Manager... In the Configuration Manager dialog, choose Debug for the configuration and Win32 for the platform. Then click Close.
The other configuration option is Release, and the other platform option is Win64. The debug option inserts extra instructions so that you can run your code in the debugger. The Win64 platform option produces 64-bit code. For what you're doing I would use Debug and Win32.

ConfigMgr.png
 
  • #12
@yungman ,

Your strategy for learning VS seems to be:
  1. Ask a question
  2. Get a series of replies
  3. Do something other than what was suggested
  4. Complain that you got bad advice or VS is broken
  5. Go to 1
Based on how this has been going, maybe it's time for a new strategy.

Back to the topic at hand. @Mark44 made a very important point that seems to have been lost:

Mark44 said:
Your program doesn't have any C-strings in it.

That should be the first thing you should change if, as you say, you want to work with C-strings. I also would not be messing around with getline: I'd work with hard-coded variables until I was sure I had it right.
 
  • Love
Likes Mark44
  • #13
I hate to go on, but...

Why would you not do this?

C-like:
std::string stl_string ("This is a string");
char * c_string = new char [stl_string.length()+1];
std::strcpy (c_string, stl_string.c_str());

If you ask "How was I supposed to know that STL string has a method named c_str that does this all for me?" My answer is that it is in the manual.
 
  • #14
Mark44 said:
"comparing all the taps" -- ? Do you mean "tops"?

The program that doesn't work isn't configured correctly. The one that works is configured to build in debug mode for the x86 architecture (i.e., 32-bit Windows). The one that doesn't work doesn't seem to be configured at all. I don't know how that would have happened.
I'm running an older version VS, but I'm pretty sure this will work in yours - on the Build menu, click Configuration Manager... In the Configuration Manager dialog, choose Debug for the configuration and Win32 for the platform. Then click Close.
The other configuration option is Release, and the other platform option is Win64. The debug option inserts extra instructions so that you can run your code in the debugger. The Win64 platform option produces 64-bit code. For what you're doing I would use Debug and Win32.

View attachment 270783
Thank you so much.
The RELEASE WORKS. Even when I change to DEBUG x86, it doesn't work. Why did it change on my on the first place? I sure did not play around with that when it went from working to error yesterday. And I notice last night when I doing the comparison and pulling down the option, I did not see the option to get the Debug and x86. So I gave up. But this morning after reading your post, I open the problem project, it had Debug and x86 on it! It seems to keep changing.

What are the Build Configurations for? How do I avoid changing them. I sure NEVER open this window and change it ever.In the image below, those are called TOPS? I did not know that. What do you call the two that said Release and x86? These are names that I consistently run into problems. That's what make it so hard to read stuffs. If you tell me to expand or collapse the folder before yesterday, I won't know what you mean.
Tops.jpg

Thanks
 
  • #15
Vanadium 50 said:
I hate to go on, but...
Right, and I didn't see any indication that this was noticed back in post #6:
C++:
ptr = new string[length];
With the assignment above, you could have the following code:
C++:
ptr = new string[length];
ptr[1] = "cats";
ptr[2] = "dogs";
ptr[3] = "elephants";
You could initialize the elements of the array up to ptr[length - 1].

yungman said:
In the image below, those are called TOPS?
No, they're not called tops. I wrote that because you said "comparing all the taps" and I was trying to figure out what you meant by "taps" . That's the menu bar, which has separate menus for File, Edit, View, Project, and so on.
 
Last edited:
  • #16
yungman said:
The RELEASE WORKS. Even when I change to DEBUG x86, it doesn't work.
It should also work in Debug x86. When you said earlier about not being able to build your program, I said that I thought it might be because of a permissions issue, which is unrelated to debug/release x86/x64.
In a different post (#10) you showed in image where it said "No configuration". My response to that was to set the configuration.
yungman said:
Why did it change on my on the first place?
No idea. Maybe poltergeists at your house. There are so many things that happen to your computer, and so many things that you do willy-nilly, that I can't come up with a good answer as to why anything happens in your programs.
yungman said:
What are the Build Configurations for?
RTFM - https://docs.microsoft.com/en-us/visualstudio/ide/understanding-build-configurations?view=vs-2019
yungman said:
How do I avoid changing them. I sure NEVER open this window and change it ever.
Keep your eyes open. Look to see what is showing.
Config.png
 
  • #17
Mark44 said:
It should also work in Debug x86. When you said earlier about not being able to build your program, I said that I thought it might be because of a permissions issue, which is unrelated to debug/release x86/x64.
In a different post (#10) you showed in image where it said "No configuration". My response to that was to set the configuration.
No idea. Maybe poltergeists at your house. There are so many things that happen to your computer, and so many things that you do willy-nilly, that I can't come up with a good answer as to why anything happens in your programs.
RTFM - https://docs.microsoft.com/en-us/visualstudio/ide/understanding-build-configurations?view=vs-2019
Keep your eyes open. Look to see what is showing.
View attachment 270795
Thanks for the reply

I toggled back and fore a few times between Release and Debug, Debug failed, Release works. This is this morning.
 
  • #18
Mark44 said:
You could initialize the elements of the array up to ptr[length - 1].

I never noticed that. Apart from confusing an array of char with an array of arrays of char, the code also gets the length wrong by one, It forgets the terminating zero.
 
  • #19
yungman said:
Debug failed, Release works.
Debug failed how? Program wouldn't compile? Wouldn't link?
We can't explain why a build failed if you don't give us more information, such as compile error number or link error number.

Did you ever get the permissions issue straightened out?
 
  • #20
Vanadium 50 said:
Apart from confusing an array of char with an array of arrays of char
It's really the difference between an STL string instance and an array of string instances.
 
  • #21
Mark44 said:
Debug failed how? Program wouldn't compile? Wouldn't link?
We can't explain why a build failed if you don't give us more information, such as compile error number or link error number.

Did you ever get the permissions issue straightened out?
See, I can just change back to debug and it failed. This is the error message, it's the same as before, that's why I did not copy the message.
Debug failed.jpg


Thanks
 
  • #22
You're right. That's what he wrote. Not what he intended - there are at least three differences between what he wrote and what he wanted: he wrote STL string when he meant C string (array of char with a terminating zero), he made it an array rather than an instance, and even if it were an instance, it's too short by one.
 
  • #23
yungman said:
This is the error message, it's the same as before, that's why I did not copy the message.
But you didn't say it was the same error as before, and that's why I asked.
The error is a linker error, LNK1104. If I do a search using LNK1104 as the search string, the first article that comes up is this one: https://docs.microsoft.com/en-us/cp...rrors/linker-tools-error-lnk1104?view=vs-2019
The first paragraph of the article is this:
This error is reported when the linker fails to open a file, either for reading or for writing. The two most common causes of the issue are:

  • your program is already running or is loaded in the debugger, and
  • your library paths are incorrect, or aren't wrapped in double-quotes.
There are many other possible causes for this error. To narrow them down, first check what kind of file filename is. Then, use the following sections to help identify and fix the specific issue.
If the program is already running or loaded in the debugger, you'll get this error.

The path that is shown in your error message has many spaces in it. You should stop including spaces in the names for your directories.
 
Last edited:
  • Like
Likes yungman
  • #24
Mark44 said:
But you didn't say it was the same error as before, and that's why I asked.
The error is a linker error, LNK1104. If I do a search using LNK1104 as the search string, the first article that comes up is this one: https://docs.microsoft.com/en-us/cp...rrors/linker-tools-error-lnk1104?view=vs-2019
The first paragraph of the article is this:

If the program is already running or loaded in the debugger, you'll get this error.

The path that is shown in your error message has many spaces in it. You should stop including spaces in the names for your directories.
Sorry, I kept seeing the same error report, I just took for granted everyone saw that.

You mean the name of my project " Copy String into C-String" has too many spaces? I notice when the name is too long, VS doesn't like it and reject out right when I create a new project. I try to be descriptive in the name so in the future when I look at the name, I know what I am looking for.

thanks
 
  • #25
yungman said:
You mean the name of my project " Copy String into C-String" has too many spaces?
Yes, way too many. If I were doing this I would name the project CopyString -- no spaces. Instead of putting the description in the project name (and the resulting filename for your project, you could create a text file or Word file with a list of the the project names and as long a description as you would like for each one.

I have several hundred projects I've done - no spaces in any of the project names.
 
  • Like
Likes yungman
  • #26
Mark44 said:
Yes, way too many. If I were doing this I would name the project CopyString -- no spaces. Instead of putting the description in the project name (and the resulting filename for your project, you could create a text file or Word file with a list of the the project names and as long a description as you would like for each one.

I have several hundred projects I've done - no spaces in any of the project names.
Thanks, now I know.

I actually when and change the name every single file in the project from "Copy String to C-String" to just CopyString. When I open the new project( new name, same project), it complained, but when I click this in the File Explorer:
Click run.jpg

It run and works. I went to Project-->Configuration Manager, it showed Debug and x86. Yes, shorten the name make it work!

THANK YOU SO MUCH. I am really learning.
Thanks
 
Last edited:
  • #27
Mark44 said:
But you didn't say it was the same error as before, and that's why I asked.
The error is a linker error, LNK1104. If I do a search using LNK1104 as the search string, the first article that comes up is this one: https://docs.microsoft.com/en-us/cp...rrors/linker-tools-error-lnk1104?view=vs-2019
Thanks for the link, this is exactly what I need. I am taking my time to read this, I also going to read the Debugger also.

I have a very simple question, I never understand what is Solution and Project. Sounds like Solution is the superset, a Solution can contain more than one project and you can choose to compile any specific project or all at one time. Am I correct?

I just want to say, unlike someone here said I don't listen and do it my own way. I listen, I ask, I learn and I write detail notes. Like I just started a folder actually printing out things that you and Jarvis linked. Those are important stuff like What your link that explain Configuration and all. Believe me, I listen and read and I don't keep repeating the mistake over and over. You seldom see me making the same mistake after I asked and understand. Like I said, I put a lot of effort writing notes for C++ and refer to my notes to write codes. Now I am doing it with VS notes also. So far, I have much less problem with C++ than VS because I have not learn VS so far until now.

Yes, I do repeat asking some question that I don't quite get and I don't necessary agree. It's not that I don't listen, I am just being critical and not follow along. Like we spent a lot of time on why the program doesn't work if I combine Add-->New file with Add-->Existing. I know you told me to do what works, But I want to be able to combine both because I feel it's important to be able to pull in pre-written external file ( .h and .cpp or objects) and use it in the program. I am sure there are better ways in later chapters, BUT, until I get to that, I still want to have a way to do that even thought it's a dumb way.

Like This one is important to me, Thanks to you, I think I've got the information so I can study deeper into it and learn more about VS. Sorry that I am not going to apologize for keep asking and being critical and sometimes not taking all the advice. I just need to think it out before I can be satisfied. That might come across that I don't listen like someone here said. I don't even trust textbooks. Yes, I wrote and CHALLENGE the author more than one occasion. When I was studying Phase Lock Loop, I read one of the most famous book by Roland Best and I wrote to challenge him on part of the book. He offered me to send me the manuscript with the correction! Only textbooks I seldom see error are Math books like multivariables, ODE and PDE that are well established. But any books on latest technology are full of typos and errors. We are all human, we make mistake.

Actually there is one example on Gaddis that I serious questioned, I type it in and it sure didn't work. I had to fix it to make it work. Sorry I don't take anyone on face value. This is how it is and everyone has to think independently.

As for why I make things more difficult for myself by making up more difficult programs. I don't go to school, I am on my own with help from you and a few others in PF. I don't have the answers of the exercise problems in the book, only way is for me to make up programs to challenge myself. I know pointers, files, structure and now class are important. So I kept stuffing those into my made up programs so I have to keep going back to my notes to write those programs. I think this really help me. The more I work, the more I perfect my notes, that becomes the blue print for my programming. I think I am learning quite fast compare with going to classes. I know from my grandson what they covered in his C++ class, I finished what he had in the class in 2 months. On top he told me they didn't even get into pointers at all. That turn out to be the most difficult part of the first 11 chapters. I've been into this for exactly 3 months to the day, I think I studied about 1 1/2 semester worth using the standard of the C++ class my grandson took as it's getting more difficult in the later chapters AND also VS. I don't study to get A in the class, I study to be the first in the class. In these days of nobody left behind, getting A and B is nothing. The only class I took in the last 30 years was ODE, imagine using multiple choice in ODE! Out of 15 questions, there's always one question: Who's the first president of US?! Just to make sure nobody get a big fat ZERO. I am not kidding. I can tell some people that got over 80% in the midterm didn't know jack of ODE! They just make the test so simple so everyone get high scores. Then they put like 20% or more of the grades on homework...which they don't even grade. You hand in some scribbles and you get the points.

Anyway, I talk too much already

Thanks
 
  • #28
yungman said:
I have a very simple question, I never understand what is Solution and Project. Sounds like Solution is the superset, a Solution can contain more than one project and you can choose to compile any specific project or all at one time. Am I correct?
Yes. Here's a screen shot of one of my programs.
MultiProj.png

The solution, DllApp, consists of two projects, DllClient and DllCode. The build rules are different for the two projects, as DllCode is compiled and linked to produce a DLL, while DllClient is compiled and linked to produce an executable (.exe) that uses two of the functions that are exported from the DLL.
yungman said:
I just want to say, unlike someone here said I don't listen and do it my own way. I listen, I ask, I learn and I write detail notes. Like I just started a folder actually printing out things that you and Jarvis linked. Those are important stuff like What your link that explain Configuration and all. Believe me, I listen and read and I don't keep repeating the mistake over and over. You seldom see me making the same mistake after I asked and understand. Like I said, I put a lot of effort writing notes for C++ and refer to my notes to write codes. Now I am doing it with VS notes also. So far, I have much less problem with C++ than VS because I have not learn VS so far until now.
The reason that you have had fewer problems with C++ is that you have benefited from the expertise of numerous members here, who have taken time to answer your questions. Many of those questions could have been answered by yourself, if you had taken time to look at the documentation for the function in question or for a particular aspect of VS. For example, your thread on getline ran for 65 posts. Another on binary files ran for 57 posts. This thread, on strings, is at 27 posts. If you had spent some time looking at the documentation that discussed the string template class, most of your questions would have been answered.
Two of your recent threads, one on a build errors and another on setting things up in VS to have multiple source files, ran for 57 posts and 89 posts respectively. Most of what you were asking about is described in detail in the VS documentation. Two of your earlier threads had 235 posts and 397 posts!
yungman said:
Yes, I do repeat asking some question that I don't quite get and I don't necessary agree.
On those points where you don't necessarily agree, is your position based on greater knowledge? If you go to someone to learn a skill, and then tell him that you don't necessarily agree about what he has said, that seems very arrogant to me.
yungman said:
It's not that I don't listen, I am just being critical and not follow along. Like we spent a lot of time on why the program doesn't work if I combine Add-->New file with Add-->Existing. I know you told me to do what works, But I want to be able to combine both because I feel it's important to be able to pull in pre-written external file ( .h and .cpp or objects) and use it in the program. I am sure there are better ways in later chapters, BUT, until I get to that, I still want to have a way to do that even thought it's a dumb way.
Sure, you can add new items and add existing items. That's easy to do, but you made it extremely difficult to help you by deleting files and folders, and wondering why the program wouldn't compile. If you had spent a little time with simple programs, as described in the VS docs and tutorials, you wouldn't have had nearly the number of problems. You would have seen how VS creates file system directories and shows different views of the program file structure in Solution Explorer.

A large part of the problem, IMO, is that you learn a little bit, and then extrapolate with your own example way beyond what you have learned. A case in point is the program you wrote in this thread using the string template class. In that program you wrote STL string when you meant C string (array of char with a terminating zero), you declared a pointer to an array of string objects rather than a single string instance, and you made to too short by one byte.

You believe this is a good way to learn -- I strongly disagree. Without the help of people here to guide you in the right direction, I believe you would still be struggling with pointers.
yungman said:
Like This one is important to me, Thanks to you, I think I've got the information so I can study deeper into it and learn more about VS. Sorry that I am not going to apologize for keep asking and being critical and sometimes not taking all the advice.
I'm going to quote a comment that @Vanadium 50 made in this thread:
Vanadium 50 said:
Your strategy for learning VS seems to be:
  1. Ask a question
  2. Get a series of replies
  3. Do something other than what was suggested
  4. Complain that you got bad advice or VS is broken
  5. Go to 1
Based on how this has been going, maybe it's time for a new strategy.
Apparently you think this is a good strategy, but it seems foolish to me. Speaking for myself, I don't mind questions, but at some point, you have to show that you have made a good faith effort to answer your question. That's also the philosophy on homework questions at this site.

yungman said:
As for why I make things more difficult for myself by making up more difficult programs. I don't go to school, I am on my own with help from you and a few others in PF.
And how do you think that some of us learned? We were on our own, as well, but without the internet to provide quick answers. How many of us learned was by looking at the documentation when something wasn't working the way we thought it would.
 
  • #29
Hi Mark

I have to stress I can't thank you and a few others enough in helping me through this leaning process. The help is invaluable for my learning of C++. It just seems like one needs knowledge to understand and find answers on line. I have to say it's seems easier now to find answer about C++ than before. I think VS is the same as this is really the first week I even try to find answer on VS. I hope it gets easier soon to find info on VS as I learn a little bit more.

I guess I am impatient in learning, I would like to get answer right away if someone have the answer. Actually I have been looking at on line classes also, somehow it doesn't seems to have the second semester class or third semester on C++. I really don't mind to pay for the class so I can go and ask questions. I know it's not fair to keep asking questions here. I am not blind, I can feel how you guys think long time ago. Paying money to ask questions is the least of my concern if I can find a source. My last hobby is designing very high end hifi power amps, I spent tens of thousands of dollars for that hobby. I have amps to show off, but now they are just sitting there.(of cause, I enjoy the sound when I watch tv!). I won't blink an eye to pay $1000 if I can find some classes on intermediate C++ online.

I have my personal problem that I never want to bore you guys out. I have neck problem. I cannot read the screen for long time. Everything I see that might help, I have to copy and paste into word file and print it out and lie down to read. Still it is very difficult for me as the pain starts to extend down to my left arm. This is life and I am not trying to get sympathy. This has been chronic problem for me in the last 35 years. I love to study, I always found jobs that was in the new area from what I had been working on in electronics so I can learn more. Like from hardware, CPU type design to high speed analog, data acquisition in digital scope company LeCroy, then to design analog IC, to Ultrasound medical scanning equipment with Siemens before settling to mass spectrometer design for 10 year. Still I venture out to communication and military defense more on RF and microwave before I retire. From the constant learning, I really racked my neck from reading. that's why reading is NOT just simple like go read the web for me. I really don't want to talk about this at all until now. It is very hard for me. Two weeks ago, I thought I have to quit studying as the pain was getting very bad and it's not worth my health to do something I don't need. Luckily I experimented and found some exercise that got me over the hump. It's not like I am looking for a job or my life depends on this. It's just fun and game all started out because of my grandson is CS major and he said he needs motivation. What is better motivation than grandpa nipping on grandson's heel! Actually to my surprise, my stepson( 56) actually picked up learn C++ because I kept talking about it. When he first talked about it a few weeks ago, I actually dismissed him, just gave him one of my book and say go for it. I thought this is only a few hours thing for him. I was surprised he actually went on line and learn and learn array and all that. Now I show him to down load VS, gave him my notes to encourage him to keep it up.

Anyway Thanks for all your help.
 
Last edited:
  • Like
Likes Mark44
  • #30
Mark44 said:
A C-string is null-terminated array of characters. A char array is just an array of characters.
C++:
char str1[] = {'C', 'a', 't'};
char str2[] = "Cat";
str1 is a character array -- no null character at the end. str2 is a C-string -- it's null terminated.
One could also in principle declare and initialize str2 as follows, no?
C++:
char str2[] = {'C', 'a', 't', '\0'};
Of course, nobody would actually do it that way in practice, but it makes explicit the fact that str2 has length 4 whereas str1 has length 3.
 
  • #31
jtbell said:
Of course, nobody would actually do it that way in practice, but it makes explicit the fact that str2 has length 4 whereas str1 has length 3.
Just to be clear, str2 has 4 bytes allocated, but its length, as determined by strlen() would be 3.
 
  • #32
Yep, I should have said "size" (which includes the terminating null in a C-string) instead of "length" (which doesn't).

Some fun with size versus length:
C++:
#include <iostream>
#include <iomanip>

using namespace std;

//--------------------------------------------------------------------------
// Display the contents of a char array as 2-digit hexadecimal numbers, etc.

void DisplayHex (char carray[], int size)
{
    cout << "as hex: ";
    for (int k = 0; k < size; ++k)
    {
        cout << hex << setfill('0') << setw(2) << (int)carray[k] << " ";
    }
    cout << endl;
    cout << "as C-string: " << carray << endl;
    cout << "sizeof = " << size << endl;
    cout << "strlen = " << strlen(carray) << endl;
}

//--------------------------------------------------------------------------

int main ()
{
    char animal[] = {'c', 'a', 't', '\0'};
    cout << "\nChar array #1:  c a t \\0" << endl;
    DisplayHex (animal, sizeof(animal));

    char animals[] = {'c', 'a', 't', '\0', 'd', 'o', 'g'};
    cout << "\nChar array #2:  c a t \\0 d o g" << endl;
    DisplayHex (animals, sizeof(animals));

    cout << endl;

    return 0;
}
Output:
Code:
Char array #1:  c a t \0
as hex: 63 61 74 00 
as C-string: cat
sizeof = 4
strlen = 3

Char array #2:  c a t \0 d o g
as hex: 63 61 74 00 64 6f 67 
as C-string: cat
sizeof = 7
strlen = 3
 
Last edited:
  • Like
Likes Vanadium 50
  • #33
yungman said:
I have to stress I can't thank you and a few others enough in helping me through this leaning process.
My oh my, how apropos!
 
  • #34
Tom.G said:
My oh my, how apropos!
What do you mean? I have been thanking everyone that help me all the time. Read my past posts. I can't say enough thanks to Mark and Jarvis lately for all the help.
 
  • #35
Hi
Other than working on the algebra problem for my grand daughter that I got stuck! :)) :)) I have been reviewing pointers again as I have to use them in exercise of Class objects. I thought I understand very well...until I really get down and step by step looking at the address and content in it in Debug. Have I learn more. I have no question, just want to say the pointers is still the hardest subject so far in C++ for me. I actually re-write this part of my notes and use a working program with Immediate Window to show step by step using break points to show the address and content how the pointers work. I attached that page of my notes. I really got into it this time.

Thanks for all the help from all you guys.
 

Attachments

  • Passing string ptr for Dynamic mem.docx
    138.3 KB · Views: 132

Similar threads

  • Programming and Computer Science
Replies
22
Views
2K
  • Programming and Computer Science
Replies
13
Views
2K
  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
Replies
5
Views
885
  • Programming and Computer Science
Replies
1
Views
880
  • Programming and Computer Science
Replies
3
Views
734
  • Programming and Computer Science
Replies
18
Views
2K
Back
Top