Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting a String to a Char Array 2

Status
Not open for further replies.

dsanow92

Programmer
Nov 15, 2005
3
0
0
US
I'm currenty using a given .txt file and comparing the first word (the correct word) to a list words. I need to see where the error is in the incorrect words, so I'm trying to convert it to a character array after I have read the word in as a string. Any idea how I would do this.

I wrote below what I thought would be simple solution it doesn't work
code:

string wORD;
char x[10];

inFile<<wORD;
char x[10] = wORD;

error is:

cannot convert from 'std::string' to 'char [10]'

What approach I should be taking?
 
You should not need to convert it to a character array. Almost everything you want to do with a character array you can do with a string. What are you specifically trying to do?

If you do need to convert it to a non const character array, you have to copy it using strcpy:
Code:
string wORD = "Hello";
char x[10];
strcpy(x, wORD);
This is very dangerous though, since wORD might be bigger than x. Another approach would be to use strncpy, or use dynamic allocation for the array. Of course, all these issues are why you should just stick to the string.

If you need a const char*, you can just use the c_str() method of the string class.

But of course, you should really ignore all that information and just tell us why you can't use the string class itself for what you are trying to do.
 
Not sure what inFile is, but for the conversion this will work.

Code:
  string sWord;
  char* x;

  inFile<<sWord;
  x = (char*)sWord.c_str();



HyperEngineer
If it ain't broke, it probably needs improvement.
 
I think it should be
Code:
inFile >> sWord;
<< is the output operator
>> is the input operator
 
Code:
x = (char*)sWord.c_str();
That is a bad idea, and might very well lead to a program crash.

You should not be modifying the internals of a string, which is why the c_str() returns a const char*. By casting it to a char*, you are breaking that contract.

If you don't need to modify the string, then you should make x a const char*, or better yet, just use the string directly.

Not sure that post deserved a star, hopefuly others don't think it means the code is a good idea. [neutral]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top