My task consists of two parts. First I have to create globbal char array of 100 elements, and insert some text to it using cin. Afterwards calculate amount of chars, and create dedicated array with the length of the inputted text. I was thinking about following solution :
char[100]inputData;
int main()
{
cin >> inputData >> endl;
int length=0;
for(int i=0; i<100; i++)
{
while(inputData[i] == "\0")
{
++count;
}
}
char c = new char[count];
Am I thinking good ?
Second part of the task is to introduce in the first program dynamically created array of pointers to all inserted words. Adding a new word should print all the previous words and if there is no space for next words, size of the inputData array should be increased twice. And to be honest this is a bit too much for me. How I can create pointers to words specifically ? And how can I increase the size of global array without loosing its content ? With some temporary array ?
Regardless of the rest of your question, you appear to have some incorrect ideas about
whileloops. Let’s look at this code.First,
"\0"is not the NUL character. It is a pointer to a string containing only the terminating NUL byte. You want'\0'instead. Assuming this change, there are still problems. Let’s work through what will happen:whileloop work? It executes the body repeatedly, as long as the condition is true.whileloop finish? When the condition is finally made false by executing the body.inputData[i] == '\0', after correction.++count.++countever change the value of the condition? No, because it doesn’t changei.inputData[i]is not the NUL byte, thewhileloop never executes.inputData[i]is the NUL byte, thewhileloop executes forever.inputData, then at some pointinputData[i]will be NUL, and you’ll have an infinite loop.To count the length of a standard C string, just do this
If for some reason you really have to write a loop, then the following works:
After the loop,
lenholds the length of the string.