+ 1
why isn't the complete string "hello world" getting printed here?
#include <iostream> using namespace std; int main() { char *s="hello world!"; for(int i=0;s[i]!='\0';++i) { cout<<*s;++s; } return 0; }
6 ответов
+ 3
Helioform is incorrect; '\0' is NOT equivalent to ' '. The null byte is equivalent to 0, and a space is 32 in ASCII. If they were the same, we wouldn't be able to have spaces in null-terminated strings.
The real reason this is happening is because you're not only incrementing i with each iteration of the loop, but you're also incrementing s. Therefore, s[i] is going to be twice as far in the string as you're expecting it to be. It's just a coincidence that it stops after "hello " (which is half the string).
To fix this, only increment one of the two variables. For example:
for (int i = 0; s[i] != '\0'; ++i)
std::cout << s[i];
+ 6
I'm gonna help you out here:
#include <iostream>
int main () {
char string[14] = "Hello, World!";
for (size_t n = 0; n < 14; n++) {
std::cout << string[n] << std::end;
}
return(0);
}
Setting a pointer to equal a string literal is very bad. Pointers are made for pointing to addresses or other data, not strings. Now, you can set it equal to a string, but this should only be done when the value of the string isn't known. Also, you could make the function even simpler but I don't know what you're aiming for so I left it out.
Oh and what was wrong is that you aren't incrementing through the array. Look at my example and note the differences.
+ 4
If you include <cstring>, you could utilize the strlen() function, which will return the number of characters in your cstring. Like this:
char* s = "hello world!";
for (int i = 0; i < strlen(s); i++) {
cout << s[i];
}
outputs: hello world!
+ 2
well that's my another question @kgomotso
+ 1
but '\0' is preceded by the entire string so the entire string should have get printed
+ 1
@sorakataduma i know what you are upto but my question is why isn't the complete string getting printed because by incrementing i.e. by p++ I'm referring to next location which should work