Help with C++ on Strings

  • Thread starter yungman
  • Start date
  • #1
5,080
120
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
 

Answers and Replies

  • #2
phyzguy
Science Advisor
4,651
1,587
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
5,080
120
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
phyzguy
Science Advisor
4,651
1,587
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
5,080
120
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
34,288
5,925
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 ( );
I have so much trouble with VS I just assume I did something wrong.
Probably a reasonable assumption.
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

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
5,080
120
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
34,288
5,925
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.
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
5,080
120
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
5,080
120
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
34,288
5,925
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
Vanadium 50
Staff Emeritus
Science Advisor
Education Advisor
2019 Award
25,664
8,854
@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:

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
Vanadium 50
Staff Emeritus
Science Advisor
Education Advisor
2019 Award
25,664
8,854
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
5,080
120
"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
34,288
5,925
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].

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
34,288
5,925
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.
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.
What are the Build Configurations for?
RTFM - https://docs.microsoft.com/en-us/visualstudio/ide/understanding-build-configurations?view=vs-2019
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
5,080
120
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
Vanadium 50
Staff Emeritus
Science Advisor
Education Advisor
2019 Award
25,664
8,854
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
34,288
5,925
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
34,288
5,925
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
5,080
120
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
Vanadium 50
Staff Emeritus
Science Advisor
Education Advisor
2019 Award
25,664
8,854
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
34,288
5,925
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
5,080
120
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
34,288
5,925
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

Related Threads on Help with C++ on Strings

Replies
6
Views
994
Top