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

  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    C++ Strings
AI Thread Summary
The discussion revolves around the challenges of copying a C++ string to a C-string and the associated memory management. The original poster seeks to allocate memory for a C-string based on the length of the input string but encounters issues with Visual Studio (VS) not compiling correctly. Experts clarify that the code provided does not actually create a C-string but rather an array of STL string objects, and they recommend using the `c_str()` method to convert an STL string to a C-string. Additionally, there are discussions about configuration settings in VS, with suggestions to run the program in different modes and ensure proper project settings to avoid compilation errors. The conversation highlights the importance of understanding the differences between C-strings and character arrays in C++.
yungman
Messages
5,741
Reaction score
294
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
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
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
 
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
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!
 
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
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
 
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
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

  • #36
Tom.G said:
My oh my, how apropos!
yungman said:
What do you mean?

He means you said "leaning" and not "learning".

yungman said:
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.

There have been 21 people who have helped you over the last bunch of threads. Deciding to thank two of them may be viewed as a snub by the other 19.
 
  • #37
Vanadium 50 said:
He means you said "leaning" and not "learning".
There have been 21 people who have helped you over the last bunch of threads. Deciding to thank two of them may be viewed as a snub by the other 19.
Did you read, I said lately. I thank everyone that help me.
 
  • #38
I just want to tell this as it can be funny...not for me!

I spent the time working on the pointers since yesterday because I have a program on Class Object that gave me like 20 error on the funniest thing. Since Class Object like the header file is similar to function but just external to the main file. So I worked on the pointers in function call to make sure I really understand this.

So I finally went back to the Class Object program...Still 20+ mistakes. Sure I saw some problems on the pointer which became very obvious after working on it. I fixed all those, but still 20+ mistakes. I started to look around because I have faith on the pointer part. Guess what I found?! I forgot to put in using namespace std; in the .h file! I put it in, it compiled one time through. Something is still not working, but this is a big step forward. Now it's just regular troubleshooting.

I am glad I spent last night and this morning to work on the pointers to pointers. Now it's crystal clear for me. I can spot the mistake in the Class program just like that!

That's why I keep making up programs to revisit the older topics in the former chapters. Now that I review pointers, dynamic memory allocations, the next is FILES, with seekp() and seekg() member functions. I feel this is the best way to learn for old leaky brain. Just do it over and over.
 
  • #39
yungman said:
I just want to tell this as it can be funny...not for me!

I spent the time working on the pointers since yesterday because I have a program on Class Object that gave me like 20 error on the funniest thing. Since Class Object like the header file is similar to function but just external to the main file. So I worked on the pointers in function call to make sure I really understand this.

So I finally went back to the Class Object program...Still 20+ mistakes. Sure I saw some problems on the pointer which became very obvious after working on it. I fixed all those, but still 20+ mistakes. I started to look around because I have faith on the pointer part. Guess what I found?! I forgot to put in using namespace std; in the .h file! I put it in, it compiled one time through. Something is still not working, but this is a big step forward. Now it's just regular troubleshooting.

I am glad I spent last night and this morning to work on the pointers to pointers. Now it's crystal clear for me. I can spot the mistake in the Class program just like that!

That's why I keep making up programs to revisit the older topics in the former chapters. Now that I review pointers, dynamic memory allocations, the next is FILES, with seekp() and seekg() member functions. I feel this is the best way to learn for old leaky brain. Just do it over and over.
Yes! As they say, "Practice makes perfect."

Don't try to rush thru everything, try for a deeper understanding before jumping forward.

Many of use will read thru most or all of the documentation before we try a new language, or even a new program. That way we get a general idea of how it all fits together and an impression of the thought processes needed to understand it.

It sounds like you are starting to get this realization, follow thru on it and you may find it actually works for you! If not, you can always fall back on what does work.

Cheers,
Tom
 
  • Like
Likes Mark44 and yungman
  • #40
Tom.G said:
Yes! As they say, "Practice makes perfect."

Don't try to rush thru everything, try for a deeper understanding before jumping forward.

Many of use will read thru most or all of the documentation before we try a new language, or even a new program. That way we get a general idea of how it all fits together and an impression of the thought processes needed to understand it.

It sounds like you are starting to get this realization, follow thru on it and you may find it actually works for you! If not, you can always fall back on what does work.

Cheers,
Tom
Thanks you for the encouragement. I needed that. Particularly I was tripped up by the algebra question from my little grand daughter. She's only freshman in high school! We Chinese called this the old cat got its whiskers burned.

Thanks
 
  • Like
Likes Tom.G
  • #41
Just a heads up, it's not good to put using namespace... in a header file. If you put it in a source file, it's usually ok because it only affects the source file, but if you do it in a header file, it applies to every file that includes it, and every file that includes a file that includes it.
 
  • Like
Likes yungman
  • #42
Jarvis323 said:
Just a heads up, it's not good to put using namespace... in a header file. If you put it in a source file, it's usually ok because it only affects the source file, but if you do it in a header file, it applies to every file that includes it, and every file that includes a file that includes it.
Thanks. Why is that so? I know I read from Mark also, but the books keep using it. I know I need to type std::cout <<...; every time if I don't use namespace std. I was wondering why my invItem.h need it. I don't have cin or cout:
C++:
#ifndef invItem_H
#define invItem_H
#include <cstring>
#include <string>
using namespace std;
class invItem
{
private:
    string* description;
    double cost;
    int units;
public:
//Constructor. pointer desc points to C-string, c for cost, u for units.
    invItem(string** desc, double c, int u)
    {
        string St2 = **desc;//St2 = St1 in main.
        int length = St2.length();
        description = new string[length];//allocate new memory using pointer description.
        *description = St2;//copy the description to memory
        *desc = description;
        cost = c; units = u;
    }
Which one of this code need using namespace std ? Do I just put std:: in front of the ones that need it? I just never look at this at all.

Thanks
 
  • #43
yungman said:
Thanks. Why is that so? I know I read from Mark also, but the books keep using it. I know I need to type std::cout <<...; every time if I don't use namespace std. I was wondering why my invItem.h need it. I don't have cin or cout:
C++:
#ifndef invItem_H
#define invItem_H
#include <cstring>
#include <string>
using namespace std;
class invItem
{
private:
    string* description;
    double cost;
    int units;
public:
//Constructor. pointer desc points to C-string, c for cost, u for units.
    invItem(string** desc, double c, int u)
    {
        string St2 = **desc;//St2 = St1 in main.
        int length = St2.length();
        description = new string[length];//allocate new memory using pointer description.
        *description = St2;//copy the description to memory
        *desc = description;
        cost = c; units = u;
    }
Which one of this code need using namespace std ? Do I just put std:: in front of the ones that need it? I just never look at this at all.

Thanks
Like I said, it's usually fine in a cpp file, but should be avoided in .h files.

The answers here explain it better than I can.
https://stackoverflow.com/questions/5849457/using-namespace-in-c-headers

std:: goes in front of string, cout, endl, ifstream, or any object from the C++ standard library.
 
  • Like
Likes yungman
  • #44
Jarvis323 said:
Like I said, it's usually fine in a cpp file, but should be avoided in .h files.

The answers here explain it better than I can.
https://stackoverflow.com/questions/5849457/using-namespace-in-c-headers

std:: goes in front of string, cout, endl, ifstream, or any object from the C++ standard library.
Thank you, no wonder I got error lining up on me! I only know cin and cout!

That I can do on the .h files from now on.
 
  • #45
I changed my .h files and use std::, works, no big deal. Just use that from now on.

I have a general, The book use C-String and char array a lot. I find using std::string a lot better. I don't have to worry about length, copying is easy, just St1 = St2 will copy over. Set up dynamic memory and file is easier. I don't see any advantage of using C-String. Not to mention, cout is easier, just cout << St1; That's it! I have been changing all the programs in the books from C-string to std::string for a while already. I hate dealing with the length when passing back and fore to function and all that.

Tell me what am I missing.

Thanks
 
  • #46
yungman said:
Tell me what am I missing.
You are missing the point that was discussed about 500 posts ago in a different thread that the ease of use of the Standard Template Library (STL) classes comes with three penalties:
  • The compier has to add the relevant parts of the STL code to your executable. If you are writing code for a microcontroller in a toaster or a fighter jet you may not have enough program memory to store it.
  • STL programs achieve their ease of use by liberal use of heap memory: for instance when you concatenate a single char to a 128 char long string it will leave the existing string on the heap and add a new string 129 chars long. If you are writing code for a microcontroller in a toaster or a fighter jet you may not have enough RAM to store it all potentially leading to burnt toast or losing control of your plane.
  • From time to time you may need to deal with an ever-growing heap by deleting the no longer needed space and moving the current references into it - this is called 'garbage collection' (GC). The STL can do this for you, or you can do it yourself but whichever way you do it you can't use the heap while it is happening. Toast that is overdone by 100 ms is not a problem, but it could be critical in say the stability controller of an aeroplane. Even with greater computing power, GC can be a problem in applications where timing is critical e.g. Digital Signal Processing (DSP).
So only use the STL when you have enough resources to do so and timing is not critical. But of course if you have plenty of resources and timing is not critical then you may as well use a more modern language than C++ that is easier to program in and debug! Microcontrollers with multi-core processors and large memories are now on the market that allow you to do exactly that e.g. in CircuitPython, Lua or Node.js.
 
  • Like
Likes yungman
  • #47
pbuk said:
You are missing the point that was discussed about 500 posts ago in a different thread that the ease of use of the Standard Template Library (STL) classes comes with three penalties:
  • The compier has to add the relevant parts of the STL code to your executable. If you are writing code for a microcontroller in a toaster or a fighter jet you may not have enough program memory to store it.
  • STL programs achieve their ease of use by liberal use of heap memory: for instance when you concatenate a single char to a 128 char long string it will leave the existing string on the heap and add a new string 129 chars long. If you are writing code for a microcontroller in a toaster or a fighter jet you may not have enough RAM to store it all potentially leading to burnt toast or losing control of your plane.
  • From time to time you may need to deal with an ever-growing heap by deleting the no longer needed space and moving the current references into it - this is called 'garbage collection' (GC). The STL can do this for you, or you can do it yourself but whichever way you do it you can't use the heap while it is happening. Toast that is overdone by 100 ms is not a problem, but it could be critical in say the stability controller of an aeroplane. Even with greater computing power, GC can be a problem in applications where timing is critical e.g. Digital Signal Processing (DSP).
So only use the STL when you have enough resources to do so and timing is not critical. But of course if you have plenty of resources and timing is not critical then you may as well use a more modern language than C++ that is easier to program in and debug! Microcontrollers with multi-core processors and large memories are now on the market that allow you to do exactly that e.g. in CircuitPython, Lua or Node.js.
Thanks so much for the reply. I did not know that. I don't recall I ever ask this question. I don't even know enough to ask.

Yes, this is VERY VERY important point. Particularly all the CPU relate design were MPU with very limited RAM. I have been talking about this all along that higher level language and all the fancy style programming assume there are unlimited amount of resources. I also complained a lot about the how slow the newer stuffs are.

Thank you.
 
  • #48
In C++ there is no garbage collection. But variable size STL containers may allocate more than they need at the moment so they don't need to reallocate so frequently. For example, if you add to a string and the new length is longer than the allocated memory, then it will need to allocate new memory. But it will always delete the old memory at that time. Also, when the string goes out of scope, the memory is freed. There will never be garbage piling up so to speak.
 
  • Like
Likes yungman
  • #49
yungman said:
The book use C-String and char array a lot.
These are almost the same, with the only difference being that a C-string is a null-terminated array of type char, and a char array is just an array of type char.
The C standard library functions rely on a string being null-terminated so that copying strings works correctly, the length is calculated correctly, appending strings works correctly, and so on.
yungman said:
C++:
#ifndef invItem_H
#define invItem_H
#include <cstring>                                   // 1) Delete this line
#include <string>                                            
using namespace std;
class invItem
{
private:
    string* description;
    double cost;
    int units;
public:
//Constructor. pointer desc points to C-string, c for cost, u for units.                   // 2) comment incorrect
    invItem(string** desc, double c, int u)
    {
        string St2 = **desc;//St2 = St1 in main.
        int length = St2.length();
        description = new string[length];//allocate new memory using pointer description.
        *description = St2;//copy the description to memory
        *desc = description;
        cost = c; units = u;
    }
The line with "#include <cstring>" should be deleted. The code shown doesn't use any C-strings.
The comment for the constructor is wrong on two counts.
1) The desc parameter is a pointer to a pointer to a string object.
2) The object being pointed to is not a C-string (which would be a null-terminated char array).
 
  • Like
Likes yungman
  • #50
Thanks guys, I am the student here, so is it not good to use strings over c-strings, or it's not that much difference? This is way beyond my head, I don't know anything on the internal mechanism of these.

My issue with C-string is when I pass into a function, if the function want to change the content before returning back to main, I have to keep track with the different length. If the return c-string is longer, that won't work as the length is defined in the main already. I have to play around with it. For strings, it doesn't matter. If it is only more complicate in compiling stage, that's ok. If it takes up much more memory during execution, that's not good.

Of cause, I can always make it longer, but then I have to be careful with the termination character. I ran into problem before that it output bunch of garbage because the array is longer than the c-string and it kept outputing garbage!

Thanks
 
Back
Top