Visual Studio 2019 requires specific compiler settings to recognize C++17 features like `string_view`. Users need to set the compiler option to `/std:c++17` in the project properties to compile code using `string_view`. A user initially faced issues with their code, which was resolved after adjusting these settings. Additionally, there were discussions about returning C-strings from functions, highlighting the importance of understanding pointers and return types in C++. The conversation emphasizes the need for clarity in error reporting and understanding basic concepts in C++.
#1
yungman
5,741
294
I am playing with string_view which is C++17, I have VS-2019, it doesn't seem to recognize string_view. I cannot even troubleshoot my program:
C++:
#include <iostream>
#include <string>
#include <string_view>
using namespace std;
int main()
{
string_view text = "Hello";
string_view str(text);
string_view more(str);
cout << text << " " << str << " " << more << "\n\n";
return 0;
}
Thanks so much Mark44. It works My program compiles.
I am really not into studying string_view. The Ivor book gave an example using string_view and I went nowhere on this. I only made up the little program to confirm it's VS.
What is that you are doing?
I was playing with this, you can actually click Project on the top bar, choose the last line PFTest3 properties and do the same thing.
Thanks so much,
#8
yungman
5,741
294
This is the program that I am trying to understand and want to translate to using c-string so I can understand it better:
C++:
#include <iostream>
#include <cstring>
#include <string>
#include <string_view>
using namespace std;
class Trouble
{
private: string message;
public:
Trouble(string_view str = " There is a problem") { message=str; }
string_view what() const { return message; }
};
void trySomething(int i)
{
if (i == 0) throw Trouble();
else throw Trouble{ " Nobody knows the trouble I've seen..." };
}
int main()
{
for (int i = 0; i < 2; i++)
{
try { trySomething(i); }
catch (const Trouble& t) { cout << " Exception: " << t.what() << "\n\n"; }
}
return 0;
}
Still working on it, it's from Ivor book.
#9
yungman
5,741
294
Please help me on this. I am translating the program in post#8 to use only c-string instead.
After I translate the program, it only print out the first letter of the string literal. eg, the first sentence is only "T" instead of "There is a problem". See output of program below.
I verified the way I pass the string literal to a function shown in line 20 to 23 and got the whole sentence "This is OutCstring test".
C++:
#include <iostream>
#include <cstring>
using namespace std;
const int csize = 51;
class Trouble
{ public:
char message[csize];
Trouble(const char *str)//Declare str pointer
{
strncpy_s(message, csize, str, csize);
cout << " message: " << message << "\n\n";//Print out "There is a problem" first
}
char what() const { return *message; }
};
void trySomething(int i)
{
if (i == 0) throw Trouble("There is a problem");//Only pass the first letter "T"
else throw Trouble( "Nobody knows the trouble I've seen..." );//Only pass letter "N"
}
void OutCstring(const char* C)//To show it passes the string literal
{
cout << " The c-string passed to OutCstring is: " << C << "\n\n";
}
int main()
{
OutCstring(" This is OutCstring test");//To proof I pass the whole sentence.
for (int i = 0; i < 2; i++)
{
try { trySomething(i); }
catch (const Trouble& t) { cout << " Exception: " << t.what() << "\n\n"; }//Only pass first letter.
}
return 0;
}
This is the output:
C++:
The c-string passed to OutCstring is: This is OutCstring test// test passing string literal to function
message: There is a problem //Print in line 11 to show message contains “There is a problem”
Exception: T //Only the first letter of the sentence “There is a problem”
message: Nobody knows the trouble I've seen... //Print in line 11 show it got copied correctly
Exception: N //Only the first letter of “Nobody knows the trouble I’ve seen……
I don't know what went wrong, please help
Thanks
Attachments
First letter.jpg
12.1 KB
· Views: 176
Last edited:
#10
Filip Larsen
Gold Member
2,036
975
yungman said:
I don't know what went wrong, please help
Try look at the return type for your what() method.
#11
yungman
5,741
294
Filip Larsen said:
Try look at the return type for your what() method.
Thanks
I kind of thinking it's the return type, I should return the message, but if I remove the '*', it flag me an error. returning *message will give the content of the address of the first element of the c-string message which is the 'T'. But I don't know how to fix it. I try everything with that line already.
Thanks
#12
Filip Larsen
Gold Member
2,036
975
yungman said:
I kind of thinking it's the return type
It is so basic I wonder how you cannot spot it yourself. You have declared the what() method to return a char. Does this match any kind of string type? If no bell rings yet then try to look at one of the many examples involving C-strings you already have discussed here on PF.
@yungman, you really, really, really need to go back and review the section on pointers. I know you've told us you know it. But you really need to learn it better. Randomly adding/removing *'s and &'s hoping it will hope shows that you don't have this down.
And getting back to the topic at hand, the reason it didn't work for you is because you need to tell VS you are using c++17. That's what @Mark44 does in his message.
#14
Filip Larsen
Gold Member
2,036
975
Vanadium 50 said:
the reason it didn't work for you is because you need to tell VS you are using c++17.
Since yungman indicate the code compiles and runs (but with, for him, unexpected results), I will maintain my earlier claim that a necessary condition to the what() to return a string is to change the return type to a string.
Did he? All he said was "I cannot even troubleshoot my program"
#16
Filip Larsen
Gold Member
2,036
975
Vanadium 50 said:
Did he? All he said was "I cannot even troubleshoot my program"
Ah, missed that you replied to the first post.
My reply is relevant for the code and question in post #8, which is the latest code sample (both now and when I replied).
#17
yungman
5,741
294
Vanadium 50 said:
@yungman, you really, really, really need to go back and review the section on pointers. I know you've told us you know it. But you really need to learn it better. Randomly adding/removing *'s and &'s hoping it will hope shows that you don't have this down.
And getting back to the topic at hand, the reason it didn't work for you is because you need to tell VS you are using c++17. That's what @Mark44 does in his message.
That is out of desperation because it doesn't make sense. I review my notes over, I NEVER managed to return a c-string from a function. I did asked here and I never got an answer, so I had to conclude I CANNOT return a c-string like that. If you know of a way, let me know.
Yes, I got that it's the VS from the very start already, that's why I asked in the first place. The error showed that it's obvious there's nothing wrong with the program, VS just won't compile without doing something. Never know VS needed to be told that it's C++17.
#18
yungman
5,741
294
I came up with a different way to return the message.
C++:
#include <iostream>
#include <cstring>
using namespace std;
const int csize = 51;
class Trouble
{ public:
char message[csize];
Trouble(const char *str)//Declare str pointer
{ strncpy_s(message, csize, str, csize); }
~Trouble() { cout << " In Trouble destructor.\n\n"; }
// char what() const { return *message; }
};
void trySomething(int i)
{
if (i == 0) throw Trouble("There is a problem");
else throw Trouble( "Nobody knows the trouble I've seen..." );
}
int main()
{
for (int i = 0; i < 2; i++)
{
try { trySomething(i); }
catch (const Trouble& t) { cout << " Exception: " << t.message << "\n\n"; }//just get the message directly!
}
return 0;
}
I just simply use t.message to get the message out. Easy peesy! I eliminated all the extra, but I added in the destructor to look at when it's out of scope.BTW, I did asked about function returning c-string here. I could not find anything in the book, I did not get any reply here. I search the web also. So I never have that in my notes. I concluded that it's NOT possible to return c-string from function. If you guys have a way, please let me know.
Also, seems like the Ivor books is the ONLY one that go deep into this exception. The C++ Primer book by Lippman arrived, it only has like 5 pages on exception, even less than Gaddis. Is exception that important? Why only Ivor put in so much effort in this? I finished Gaddis 20 pages in less than a week. All the time and debate are from the Ivor book. If exception is not that important, I am going to stop here. I already learn a lot more than in Gaddis book already. I want to move onto Template.
Thanks
Filip Larsen said:
Ah, missed that you replied to the first post.
My reply is relevant for the code and question in post #8, which is the latest code sample (both now and when I replied).
That's two completely different questions. My first question in OP is about VS, that was resolved thanks to Mark44. I just tagged on the second question in post 8. Vanadium50 mixed the two together.
#19
Filip Larsen
Gold Member
2,036
975
yungman said:
I did asked about function returning c-string here. I could not find anything in the book, I did not get any reply here. I search the web also.
You could also try "what is a c-string" and see if that brings more light to your understanding of this.
The literature and the web is simply stock full of char * and const char *, and I have a hard time imagining how you could getting this far in your C++ exercises without never noticing what a C-string is. As you have been told by many by now, it is very difficult to assist you with appropriate hints when you "suddenly" are completely blank on some of the most basic concept.
You could also try "what is a c-string" and see if that brings more light to your understanding of this.
The literature and the web is simply stock full of char * and const char *, and I have a hard time imagining how you could getting this far in your C++ exercises without never noticing what a C-string is. As you have been told by many by now, it is very difficult to assist you with appropriate hints when you "suddenly" are completely blank on some of the most basic concept.
I tried before, I can't find a way to make it work. This is the program I was working on, you can see the one in the middle doesn't work.
You should also review functions. A function that returns a string would need to have a string type. But C does not have a string type. (It does. however, have a pointer type)
#23
yungman
5,741
294
Vanadium 50 said:
You should also review functions. A function that returns a string would need to have a string type. But C does not have a string type. (It does. however, have a pointer type)
That's what I am talking about. I failed to see a way with this. I spent a lot of time on this. I know I can work around like in my final program bypass that. That's easy. My question is specifically on return c-string from a function.
I'll be really thankful if you can help making the middle one work. That's the essence of return a c-string. I really worked on it. I got so desperate I put '*' and const blindly all over already.
Hey, you can be logical, BUT if none work, the NEXT logical step is to go illogical!:)
My question is specifically on return c-string from a function.
And you cannot do that. I've told you twice, Filip has told you once, and that's this thread. In your previous thread, Mark44 tells you twice, Jarvis323 tells you twice, and Halc and sysprog each tell you once. And if I searched more threads, I would find more examples.
Mark44 said:
It's disrespectful to us and wasteful of our time when we answer a question that you've asked, and you don't read the responses, and ask the same question again.
You really need to go back to the chapters on functions and pointers.
1. A function cannot return a C-string in C. (Or C++)
2. A function can return a pointer to a C-string. However, one must take care to ensure this pointer points to the string, and not a memory location where the string used to be.
That's because retCstring2() is returning a dangling pointer. The array Cret[] is a local variable which goes out of scope as soon as the function returns. So, the pointer returned by retCstring2() points to memory that is no longer available.
The result is undefined behavior. If you're lucky the memory won't yet be overwritten when you try to use the pointer returned by retCstring2() , but in general this is not guaranteed. In the real world, Murphy's Law means that it will work when you test it, you'll ship it to customers, and it won't work for them.
As I've mentioned in a previous message in another thread, the only way to do what you're trying to do is to allocate an array of storage using new, copy the string into that array, and return a pointer to that array.
But then the burden falls on the caller of your function to delete the storage. This leads to all sorts of memory leaks when users fail to do so. The natural thing to do is to create a class that performs the new in the constructor and the delete in the destructor, hence cleans up after itself. But this is just a very poor duplication of what std::string already does, so why not use std::string?
The only other alternative is something like your Trouble implementation, which uses a fixed-size array and thereby avoids the new/delete issue. But this is a poor solution because it imposes a maximum string length (the size of the array must be a constant known at compile time), and every instance of this class will require the maximum fixed storage size, even if only using a tiny part of it!
No one should be messing around with C strings in 2021 unless they have a very good reason, such as (1) they're on a compiler team implementing the standard library, hence have to write std::string from scratch, or (2) they're on a primitive embedded platform that doesn't provide dynamically allocated memory and therefore cannot provide a std::string implementation.
No one should be messing around with C strings in 2021 unless they have a very good reason, such as (1) they're on a compiler team implementing the standard library, hence have to write std::string from scratch, or (2) they're on a primitive embedded platform that doesn't provide dynamically allocated memory and therefore cannot provide a std::string implementation.
In the real world, we write exceptions in C++ to throw objects with integer (enum) error codes. If a human language message needs to be displayed/logged this can be dealt with in the error handling block of the calling code.
#28
Filip Larsen
Gold Member
2,036
975
jbunniii said:
No one should be messing around with C strings in 2021
I have been saying that from the start too! But someone here keep insisting on continuously experiencing and share how easy is it to shoot yourself in the foot (or other appropriate body part) with these strings .
(For the record, I give said someone plus points for stamina, but minus point for not learning from earlier mistakes - and myself minus points for keep falling into the trap of answering ).
#29
yungman
5,741
294
Filip Larsen said:
I have been saying that from the start too! But someone here keep insisting on continuously experiencing and share how easy is it to shoot yourself in the foot (or other appropriate body part) with these strings .
(For the record, I give said someone plus points for stamina, but minus point for not learning from earlier mistakes - and myself minus points for keep falling into the trap of answering ).
The reason is Gaddis book mainly use c-string for everything. I am still using the Gaddis and do the exercise. Gaddis book still have the best program examples, even have CD that contain all the programs. I cannot just drop it. I have no choice at this point! After learning exception,Templates and the few chapters on data structure, then if I have time, I can go back in the future, but not now.
Yes, I notice Ivor book and the newly acquired C++ Primer by Lippman both exclusively using std::string. Lippman book is better than Ivor, BUT it really doesn't have complete program that I can work on, just snipped of codes. Ivor is hard to understand period, we went through a big debate on that already. Lippman book is better for reading. So I am still confined to reading Lippman and working on Gaddis...Meaning a lot of c-string.
Also, c-string is faster in run time than std::string. I have to learn string_view of C++17 to speed it up. That's one more to learn for me where I am trying to finish Gaddis book.
Yes, I notice std::string is much easier to use.
#30
Filip Larsen
Gold Member
2,036
975
yungman said:
I notice Ivor book and the newly acquired C++ Primer by Lippman both exclusively using std::string. Lippman book is better than Ivor, BUT it really doesn't have complete program that I can work on, just snipped of code.
I am not familiar with Lippman's book, but hopefully you should quickly be able to work those snippets into your own context pretty quickly (just like you seem to do with the code you have from Gaddis).
yungman said:
c-string is faster in run time than std::string.
Even if that claim was true (which I strongly doubt; modern std::string or similar implementations are highly optimized for performance while still maintaining easy and safe use), I can't help wondering what kind of program you plan to make where you think any performance difference between the two will be an issue?
I ask because run-time performance obviously does not matter one bit when you are just learning the basics, so if you are worried about speed you must be thinking of some usage situation and not about learning, right?