Hi,
I am trying to create a string object from a char array.
My char array has "This house is nice"
string tempStr(MyCharArray);
tempStr now has "This", which is wrong!
How can I can put the whole line in my string object? thanks.
Printable View
Hi,
I am trying to create a string object from a char array.
My char array has "This house is nice"
string tempStr(MyCharArray);
tempStr now has "This", which is wrong!
How can I can put the whole line in my string object? thanks.
I don't know why that is happening but char* isn't an array. Thats a pointer. char blabla[50] is an array
The following code works fine for me. I'm using MSVC++ 6.0, what about you?
Code:#include <string>
#include <iostream>
using namespace std;
int main()
{
char* MyStringArray = "This house is nice.";
string tempStr(MyStringArray);
cout << endl << tempStr << endl; // Prints out "This house is nice."
return 0;
}
I am aware of the difference. Here's the code snippet:Quote:
Originally posted by ErionD
I don't know why that is happening but char* isn't an array. Thats a pointer. char blabla[50] is an array
<code>
nom = new char[50];
char* ptr = &tamp[4]; // location 4 is where the name begins
while (ptr)
{
if (isspace(*ptr) || *ptr == '\0')
nom[i++] = ' ';
else
nom[i++] = *(ptr++);
if (isspace(*ptr) && isspace(*(ptr + 1)))
{
nom[i] = '\0';
string nomm(nom);
prod->setNom(nomm);
break;
}
}
</code>
basically, I am reading a name of a product from a file. The name is multi names separated by space and ended by double spaces.
do you guys know of a way to tokenize on double space?
The code I posted above is ugly and doesn't really do the job. If I use strtok(myStringArray, " "), it will still tokenize on ONE space rather than two spaces.
Thanks for the feedback y'all.
I think your code is flawed, because as soon as it hits a space, ptr is no longer incremented:
Code:if (isspace(*ptr) || *ptr == '\0')
nom[i++] = ' ';
else
nom[i++] = *(ptr++);
This is actually a tad incorrect. array[50] actually defines a pointer which points to the first item in an array. Example:Quote:
Originally posted by ErionD
I don't know why that is happening but char* isn't an array. Thats a pointer. char blabla[50] is an array
char blah[10]="hello";
cout << blah << endl << (blah+1) << endl;
This would produce:
hello
ello
That is why you specify char* when passing an array of character to a function/method, because in actuality it is a pointer to the start of the string.