HDK: Can you fill a UT_String from stdin?

   3450   5   1
User Avatar
Member
18 posts
Joined: 7月 2005
Offline
I know this used to work:


#include <iostream>
#include <UT/UT_String.h>
using namespace std;
int main() {
UT_String bar;
printf(“gimme: ”);
cin >> bar;
printf(“%s\n”,(char*)bar);
return 0;
}
but 9.5 doesn't seem to like it.

What's the best way to fill a UT_String from stdin?
software dude @ Asylum
User Avatar
スタッフ
1454 posts
Joined: 7月 2005
Offline
You could try UT_WorkBuffer class (see comments in the header file):

#include <iostream>
#include <UT/UT_String.h>
#include <UT/UT_WorkBuffer.h>
using namespace std;
int main() {
UT_String bar;
UT_WorkBuffer buffer;
printf(“gimme: ”);
buffer.getline(cin);
printf(“buffer: %s\n”, buffer.buffer());
buffer.copyIntoString(bar);
printf(“str: %s\n”, bar.buffer());
return 0;
}
User Avatar
Member
18 posts
Joined: 7月 2005
Offline
rafal
You could try UT_WorkBuffer class (see comments in the header file):
Didn't know about that class, thanks.

However, if there's converting that's going to take place, I may as well just use ANSI strings… which I did & now everything is back to working like before.

Thanks for the clarification.
software dude @ Asylum
User Avatar
Member
7871 posts
Joined: 7月 2005
Offline
I don't see how you can do that safely with ANSI strings though. Take for example, "char str; cin >> str". Now what happens if the user types in more than 4 characters? You might not crash of course until the user types in more than 16 characters due to memory alignment but doing so is definitely not safe.
User Avatar
Member
18 posts
Joined: 7月 2005
Offline
edward
I don't see how you can do that safely with ANSI strings though. Take for example, "char str; cin >> str". Now what happens if the user types in more than 4 characters? You might not crash of course until the user types in more than 16 characters due to memory alignment but doing so is definitely not safe.
maybe “ANSI string” is not the correct term. I mean…

#include <string>
#include <iostream>
#include <UT/UT_String.h>
using namespace std;
int main() {
UT_String myUT;
string mySTR;
cin >> mySTR;
myUT = mySTR.c_str();
return 0;
}
software dude @ Asylum
User Avatar
スタッフ
1454 posts
Joined: 7月 2005
Offline
note that in some cases you may want:

myUT.harden( mySTR.c_str() );

instead of

myUT = mySTR.c_str();


because the last one does only a shallow copy (unless you use UT_String::ALWAYS_DEEP in the myUT construction) and once mySTR goes out of scope that string will be deleted. Here, the last code snippet is fine because myUT is not used beyond the scope of mySTR.
  • Quick Links