can c-string's be created dynamicaly

Started by
17 comments, last by Zahlman 14 years ago
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) == 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) == consonants[j])			{				counter++;			}		}	}return counter;}
Advertisement
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.
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.

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.
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.
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.
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]
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.
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.

This topic is closed to new replies.

Advertisement