string

#include<iostream>
#include<conio.h>
#include < string.h>
#define size 20
using namespace std;

void main()
{
char *str1 = "Dulplication";
while ( str1 !='\0')
cout << str1;

getch();
}
i cannot stop it.this program will continue cout dulplication.Please help me.
Thank you very much.
When do you want it to stop? Delete the line while ( str1 !='\0'). Or do something with str1, as to transform it to '\0'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//maybe this you need...

#include<iostream>
#include<conio.h>
#include < string.h>
#define size 20
using namespace std;

void main()
{
char *str1 = "Dulplication";
while (*(str1) != '\0'){
	cout << *(str1);
	str1++;

	getch();
}


}
Last edited on
Yes, thank you for you helping.
can i know the reason why use pointer can do ?
You do not understand while loops correctly, or, given the current evidence, general logic flow.

You have to specify everything.

while(str1 != '\0')

will loop until the array is equal to the null character. If the entire string does not equal the null character, it will keep looping. Since you never do set the string to a null character, it loops forever.

I believe the appropriate function would be a for loop for this case:

1
2
3
4
for(unsigned int x = 0; str[x] != '\0'; x++)
{
    //display the "x"th character in the string, I'll leave this to you
}
Last edited on
The problem is the while-loop: Once the term is nut \0, the while loop will run into INFINITY.
you have to build a do while loop and question the enter at the very end or beginning ofvthe loop.
Jetkeynature:

No. Please do not post unless you understand. The string will never be equal to "\0" because it is never set to "\0". You do not need a whle loop if you're just going to use cout.operator<<(const char*) on it.
Last edited on
Also void main() is not legal C++ and you should always use int main() always always.
I use while is due to the question requirement,and one more, according to my knowledge the string will have one'\0' at the end.

Thank you for your help.
The you need to use char& string.operator[](unsigned int&) on the string then.

1
2
string s("Hello World!");
for(auto ch : s) cout<< ch;


to get an element of a string:

1
2
3
4
5
if(s.size() > 0)
{
    cout<< "The first character is \'"<< s[0]<< "\'."<< endl;
    cout<< "The last char is \'"<< s[(s.size() - 1)]<< "\'."<< endl;
}


I have to critisize your professor, though. A while loop is a poor way to perform the task of displaying a string. It's probably even discourage-able.

OF COURSE, you could always just:

1
2
string s("Hello World!");
cout<< s<< endl;


God forbid we write it like it was meant to be written... I would be such a smart-ass student... LOL
Last edited on
Topic archived. No new replies allowed.