Sign in to follow this  
kingpinzs

can c-string's be created dynamicaly

Recommended Posts

kingpinzs    117
can I creat a c-string synamicaly since I dont know how much data will be entered. Is there a way to let the user enter a bunch of data and the read the size to creat a c-string?

Share this post


Link to post
Share on other sites
way2lazy2care    790
I'm guessing english isn't your first language as you're from germany.

Could you try explaining your problem/question a little more in depth? It could make perfect sense to others, but I'm a little confused on what you're actually asking for.

Share this post


Link to post
Share on other sites
kingpinzs    117
instead of

const int SIZE = 100;
char input[SIZE];

cout<<"Enter a string ";
cin.getline(input, SIZE);

I want the user to be able to input a string as long as they want then I creat the char to use it.

some thing like

char *input;

cin<< as much data as they want

input = new char(x.size)

Share this post


Link to post
Share on other sites
phresnel    953
Quote:
Original post by kingpinzs
Quote:
Original post by phresnel
In C++?


I know I can use a string but I want to use a c-string
its easyer for me to minipulate a c-string then a string class


So easy that your code is bugfull and dangerous, open to many kinds of malicious attacks. Something that nobody should install on his machine.

Just use string and be done:

#include <iostream>
#include <string>
int main () {
std::string name;
std::getline(std::cin, name);
}



For formatting strings, use stringstream:

#include <sstream>
int main () {
std::stringstream ss;
ss << 42 << 0.5f << 0.5 << "hello world" << '\n';
std::cout << ss.str();
}

Share this post


Link to post
Share on other sites
jyk    2094
Quote:
I know I can use a string but I want to use a c-string
its easyer for me to minipulate a c-string then a string class
std::string is most likely exactly what you are looking for.

Can you give an example of how C strings are easier to manipulate? Almost any string-related operation I can think of is simpler, safer, and takes fewer lines of code with string than with a raw character array.

(I'm not saying there's never a reason to prefer C-style strings, but 'easier to manipulate'? That seems a bit odd.)

Share this post


Link to post
Share on other sites
kingpinzs    117
Quote:
Original post by phresnel
Quote:
Original post by kingpinzs
Quote:
Original post by phresnel
In C++?


I know I can use a string but I want to use a c-string
its easyer for me to minipulate a c-string then a string class


So easy that your code is bugfull and dangerous, open to many kinds of malicious attacks. Something that nobody should install on his machine.

Just use string and be done:

}[/code]


First of all this is personal use and not to be used by any one else.
Its a consule app to learn how c++ works
Also in my c++ class in collage we had to do a full chapter on c-string and I was just wondering if they could be created dynamicaly

and third


char menu();
int vowel_counter(char *);
int consonants_counter(char *);
void cls( HANDLE );

int main()
{
const int SIZE = 100;
char input[SIZE];
char menu_input;

cout<<"Enter a string ";
cin.getline(input, SIZE);


menu_input = menu();

while(toupper(menu_input) != 'E')
{
if(toupper(menu_input) == 'A')
{
cout<<"The number of vowels in your string is "<<vowel_counter(input)<<endl;
cout<<"Press a key to continue"<<endl;
cin.ignore();
cin.get();
}
else if(toupper(menu_input) == 'B')
{
cout<<"the number of consonants in your string is "<<consonants_counter(input)<<endl;
cout<<"Press a key to continue"<<endl;
cin.ignore();
cin.get();
}
else if(toupper(menu_input) == 'C')
{
cout<<"The count of both consonants and vowels is "<<vowel_counter(input) + consonants_counter(input)<<endl;
cout<<"Press a key to continue"<<endl;
cin.ignore();
cin.get();
}
else if(toupper(menu_input) == 'D')
{
cout<<"Enter a string ";
cin.ignore();
cin.getline(input, SIZE);
}

menu_input = menu();
}

cout<<"Exiting the program "<<endl;
system("PAUSE");
return 1;
}


char menu()
{
HANDLE hConsole; hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
cls(hConsole);
char input;
cout<<"\t\tCount Vowels, Consonants or Both."<<endl<<endl;
cout<<"\t A) Count the number of vowels in the string"<<endl
<<"\t B) Count the number of consonants in the string"<<endl
<<"\t C) Count both the vowels and consonants int the string"<<endl
<<"\t D) Enter another string"<<endl
<<"\t E) Exit the program"<<endl<<endl
<<"\t Enter a letter ";
cin>>input;
return input;
}

int vowel_counter(char *cString)
{

char vowles[5]={'A', 'E','I', 'O', 'U'};
int counter = 0;

while(*cString != '\0')
{
for(int i = 0; i<5; i++)
{
if(toupper(*cString) == vowles[i])
{
counter++;
}
}
cString++;
}

return counter;
}

int consonants_counter(char *cString)
{
char consonants[21]={'B', 'C','D', 'F', 'G', 'H' ,'J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z'};
int counter = 0;

while(*cString != '\0')
{
for(int i = 0; i<21; i++)
{
if(toupper(*cString) == consonants[i])
{
counter++;
}
}

cString++;
}

return counter;
}



This is how it is easyer to use

Share this post


Link to post
Share on other sites
phresnel    953
Quote:
Original post by kingpinzs
Its a consule app to learn how c++ works

This is how C works, to which C++ is mostly compatible.


Quote:
Also in my c++ class in collage we had to do a full chapter on c-string and I was just wondering if they could be created dynamicaly

If this is a 101 class, than they shouldn't be teaching raw string manipulation.

But if you really need it, you should at least use the "n" versions from <cstring>. And the only way for doing what you want (that is, reading in an arbitrary sized string, i.e. where a SIZE-constant is conceptually wrong) is char-wise reading, and keeping the input characters in a container, until '\n' is read.


Quote:
and third

*** Source Snippet Removed ***

This is how it is easyer to use

No, that's not easier.

Also, programs shouldn't halt once they are finished, especially not through spawning a new process.

Share this post


Link to post
Share on other sites
Evil Steve    2017
Quote:
Original post by kingpinzs
*** Source Snippet Removed ***

This is how it is easyer to use


It's just as easy with std::string:

char menu();
int vowel_counter(const std::string&);
int consonants_counter(const std::string&);
void cls( HANDLE );

int main()
{
std::string input;
cout<<"Enter a string ";
std::getline(std::cin, input);

char menu_input = menu();
while(toupper(menu_input) != 'E')
{
if(toupper(menu_input) == 'A')
{
cout<<"The number of vowels in your string is "<<vowel_counter(input)<<endl;
cout<<"Press a key to continue"<<endl;
cin.ignore();
cin.get();
}
else if(toupper(menu_input) == 'B')
{
cout<<"the number of consonants in your string is "<<consonants_counter(input)<<endl;
cout<<"Press a key to continue"<<endl;
cin.ignore();
cin.get();
}
else if(toupper(menu_input) == 'C')
{
cout<<"The count of both consonants and vowels is "<<vowel_counter(input) + consonants_counter(input)<<endl;
cout<<"Press a key to continue"<<endl;
cin.ignore();
cin.get();
}
else if(toupper(menu_input) == 'D')
{
cout<<"Enter a string ";
cin.ignore();
cin.getline(input, SIZE);
}

menu_input = menu();
}

cout<<"Exiting the program "<<endl;
system("PAUSE");
return 1;
}


char menu()
{
HANDLE hConsole; hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
cls(hConsole);
char input;
cout<<"\t\tCount Vowels, Consonants or Both."<<endl<<endl;
cout<<"\t A) Count the number of vowels in the string"<<endl
<<"\t B) Count the number of consonants in the string"<<endl
<<"\t C) Count both the vowels and consonants int the string"<<endl
<<"\t D) Enter another string"<<endl
<<"\t E) Exit the program"<<endl<<endl
<<"\t Enter a letter ";
cin>>input;
return input;
}

int vowel_counter(const std::string& str)
{
char vowles[5]={'A', 'E','I', 'O', 'U'};
int counter = 0;

for(size_t i=0; i<str.length() ++i)
{
for(int j=0; j<5; ++j)
{
if(toupper(str[i]) == vowles[j])
{
counter++;
}
}
}

return counter;
}

int consonants_counter(const std::string& str)
{
char consonants[21]={'B', 'C','D', 'F', 'G', 'H' ,'J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z'};
int counter = 0;

for(size_t i=0; i<str.length() ++i)
{
for(int j=0; j<5; ++j)
{
if(toupper(str[i]) == consonants[j])
{
counter++;
}
}
}

return counter;
}

Share this post


Link to post
Share on other sites
kingpinzs    117
by the way that wast the assienment out of the book and it is c++ 101 right after pascal.

Also the book is called starting out with c++ from control structures through objects by tony gaddis. so blaim him I am just follwoing the assinemnt

but I just thought that if i could dynamicly creat a c-string or an array of chars then it whold make the program more usable.
and also I halt it that way so my professor can see the results. instead of just blicking on the screen. Yes I know you can use cin.get but he doesnt care as long as he can see it

that is a mute point becuase I would never sell anything in consule mode any way to me its not very user freindly.
its better to use buttons and things.

Share this post


Link to post
Share on other sites
kingpinzs    117
Quote:
Original post by Evil Steve
Quote:
Original post by kingpinzs
*** Source Snippet Removed ***

This is how it is easyer to use


It's just as easy with std::string:
*** Source Snippet Removed ***


But then I would get the problem wrong.

Directly out of the book
Write a function that accepts a pointer to a C-string as its argument.

so no I cant use strings.

Share this post


Link to post
Share on other sites
jyk    2094
Quote:
This is how it is easyer to use
No, there is nothing in that example that shows raw character arrays to be easier to use than std::string.

There are plenty of reasons one might need or want to use C strings (it's part of an assignment, you want to learn about low-level programming techniques, etc.), but 'ease of manipulation' isn't very high on that list. If you think C strings are easier to manipulate, I'm guessing it's just because you have little or no experience using std::string.

Share this post


Link to post
Share on other sites
jyk    2094
Quote:
But then I would get the problem wrong.

Directly out of the book
Write a function that accepts a pointer to a C-string as its argument.

so no I cant use strings.
Well, initially you said:
Quote:
I know I can use a string but I want to use a c-string
its easyer for me to minipulate a c-string then a string class
Which is different.

In any case, learning about low-level manipulation of strings is not a bad idea at all, IMO, but it's a good idea to learn about available tools such as std::string as well.

Share this post


Link to post
Share on other sites
kingpinzs    117
Quote:
Original post by jyk
Quote:
This is how it is easyer to use
No, there is nothing in that example that shows raw character arrays to be easier to use than std::string.

There are plenty of reasons one might need or want to use C strings (it's part of an assignment, you want to learn about low-level programming techniques, etc.), but 'ease of manipulation' isn't very high on that list. If you think C strings are easier to manipulate, I'm guessing it's just because you have little or no experience using std::string.


You would be geussing write.
Also becuase its just logical to me a char and array of chars and I figure the string class just has functions that do the char minipulation for you.

Share this post


Link to post
Share on other sites
phresnel    953
Quote:
Original post by kingpinzs
by the way that wast the assienment out of the book and it is c++ 101 right after pascal.

Ouch. Okay, in the meanwhile we know that most programming teachers are straight ignorant. Same for a plethora of books.


Quote:
but I just thought that if i could dynamicly creat a c-string or an array of chars then it whold make the program more usable.

As said, you can. But the correct way would include reading character by character, until a terminator is found (e.g. '\n'). Upon reading it, you must keep book, in a container from the stdc++-library (e.g. vector), or by writing your own c-style linked list. This is the way to do things if you don't know the size beforehand.


Quote:
and also I halt it that way so my professor can see the results. instead of just blicking on the screen. Yes I know you can use cin.get but he doesnt care as long as he can see it

While cin.get() would be better than spawning a whole process in system("PAUSE"), and would make your C++ program portable and not only run on Windows (okay, it would also run on other systems, but PAUSE could be everything there, like PAUSING the whole operating system), it is still a bad idea to halt a program after it has finished. Better use the right option in the IDE you use, one that states "halt after finishing" or similar, or run your binary from the console.

Not halting, but to die is the right thing. People die once they are finished with life, and don't halt in a freeze position. You don't halt the garbage of your meal in the kitchen, but let it die in the depot. Et cetera.

Quote:
that is a mute point becuase I would never sell anything in consule mode any way to me its not very user freindly.

GUI is not equal to user friendly. Personally, I find git much more enjoyable on the command line than through a pumped up GUI. Or think of daemons/services, device drivers, compilers, debuggers, profilers. All those have no GUI, and none of them halts after work is done.


...

Quote:
char and array of chars

In
const char *p = "hello world";

you have a string literal and a pointer to it. But there is no array.

An array of char goes like this:
char a[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};




edit: one more note: I know at least 5 IDEs that have a terminal which prints out stderr/stdout/stdlog: Code::Blocks, Anjuta, KDevelop, QtCreator, MSVC.

[Edited by - phresnel on March 30, 2010 3:35:33 AM]

Share this post


Link to post
Share on other sites
DevFred    840
Quote:
Original post by phresnel
In
const char *p = "hello world";

you have a string literal and a pointer to it. But there is no array.

Yes there is. The type of "hello world" is const char[12], and p points to the first element of that array.

If there was no array, evaluating p[1] (which is translated into *(p+1)) would be illegal, because pointer arithmetic is only well-defined for pointers that point into arrays.

You could even point to the entire array:

const char (*q)[12] = &"hello world";

I don't see why you would want to do this, but it proves my point.

Share this post


Link to post
Share on other sites
Zahlman    1682
Quote:
Original post by kingpinzs
instead of

const int SIZE = 100;
char input[SIZE];

cout<<"Enter a string ";
cin.getline(input, SIZE);

I want the user to be able to input a string as long as they want then I creat the char to use it.

some thing like

char *input;

cin<< as much data as they want

input = new char(x.size)


Try thinking about this for a second.

You want to input data into a buffer, without knowing how much data there will be ahead of time. Then, measure the amount of data and allocate space for it.

How will you know that there is enough room in the buffer?

The size of any kind of buffer has to be set ahead of time. If there is more data than the buffer can hold, then you have to detect when the buffer is full, move the data somewhere, and then start reading into the buffer again.

The getline() function you are using will read up to the amount of data that you specify. You specify the size of the buffer you are using, so that the buffer will not overflow. If the buffer gets filled and there is still more data, the 'fail' bit is set on the stream, so you can check for that.

So, you will need a loop something like this:


To append string 'x' to string 'y', given 'len' is the length of 'y':
Increase 'len' by the length of 'x' - 1.
(The -1 is because there is a null terminator in the buffer that we won't be appending)
Allocate len-many bytes into 'temp'.
Copy string data from 'y' to 'temp'.
Append string data from 'x' to 'temp' (starting by over-writing the null terminator from the 'input' data).
Deallocate 'y'.
Point 'y' at 'temp'.

'input' points to a new array of 1 character, with the value '\0'.
(That allows uniform handling inside the loop).
'buffer' is an empty array of chars.
'len' is a counter for the length of the data 'input' points at.

Repeat:
Read from cin into 'buffer', up to the size of 'buffer'.
If the fail bit is set on cin:
Append 'buffer' to 'input' by the above process.
Reset the fail bit on cin.
Otherwise:
Exit the loop.
Append 'buffer' to 'input' by the above process. (To handle any "left-over" part).



Complicated, isn't it? That's what std::string is for. It's actually smarter than that, because there is a real object holding the 'len' and 'input' values together, and a smarter (but more difficult) idea is used for re-allocating the memory, and there may be a small buffer built in so that heap-allocation is not needed for very short strings.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this