This question already has answers here:
What does while(*pointer) means in C?
(5 answers)
Closed 5 years ago.
This code will print a string of characters:
const char* aString = "This is a string";
const char* ptrString = aString;
while(*ptrString)
{ std::cout << *ptrString;
ptrString++;
}
I'm still a newbie. From what I had learnt so far, while loop always has a condition inside the bracket like while(x<10) or something. I just don't understand why does the while loop in this case has only *ptrString as its condition. What does it actually mean? Can somebody explain to me?
When the pointer reaches the end of the string it finds an end of string character which value is 0, which evaluates to false when casting to bool. Then the loop ends.
while(*ptrString)
It stops when the *ptrString is null character. As ptrString is incremented in ptrString++;, eventually *ptrString will point to null character.
You can simplify the loop body to
std::cout << *ptrString++; // Ideal use of post-fix operator
though..
Related
This question already has answers here:
What is an off-by-one error and how do I fix it?
(6 answers)
Closed 1 year ago.
I came across a scenario where string concatenation is failing in C++. But I don't see a reason for it to fail.
Code sample is as below:
int main()
{
std::string a;
std::string b = "bbbbbbb";
a.resize(10);
for (int i = 0; i <= 5; i++) {
a[i] = 'a';
}
a = a+b;
printf("\n%s\n", a.c_str());
}
It is outputting aaaaaa.
I was expecting it to output aaaaaabbbbb. If I change a.resize(10); to a.resize(5); I am getting the expected output.
Would be helpful if someone could help me in understanding the behaviour?
In addition to the off-by-one error, after concatenation, the contents of a in main are:
aaaaa\0\0\0\0\0bbbbb
So: five 'a' bytes, then five zero bytes, then five 'b' bytes. The string is fifteen bytes long.
printf, like other C functions, doesn't know about this size, and instead takes the length of the string to be until the first zero byte. In your case, that is "aaaaa".
To print the entire string, use something like std::cout. If you're certain you want printf, it is also possible to pass a length to that with the %.*s specifier.
std::string a;
a.resize(10);
gives you a string of size 10 but whose content is undefined.
You set the first 5 character to something specific and append some more characters to the end. But characters 5-10 never get set to something.
In the execution you are seeing, these characters happen to be zero, but printf – as a C style function — considers the appearance of a null character the end of the string. Therefore it stops printing.
This question already has answers here:
strlen() on non-null-terminated char string?
(9 answers)
Closed 4 years ago.
#include<iostream>
#include<string.h>
using namespace std;
int main() {
char b[] = {'a','b',' ','c'};
cout << sizeof(b) << endl;
cout << strlen(b) << endl;
return 0;
}
Why the above output is 4,6 isnt that 4,4 is the correct answer?
The behaviour of your code is undefined: strlen requires that b must contain a NUL character within the bounds of the array.
(Note that ' ' is a space, not NUL. A space is processed no differently by strlen to any other non-NUL character.)
If you had written
char b[5]={'a','b',' ','c'};
then C++ would have set the final element of b to 0 (i.e. NUL) for you.
what does strlen do if it enounter a space in between char array?
While all the other answers (according to your code sample, legitimately!!!) hint to the undefined behaviour due to the missing null character within your array, I'll be answering your original question:
Nothing special, it will count the space just as any other character (especially, it won't stop processing the string as you seem to have assumed)...
Your code exhibits undefined behavior:
The behavior of strlen is not defined if the argument passed to it is not NUL-terminated.
You seem to confuse the NUL character with the space character.
strlen traverses the array until it encounters a NULL character. Your array does not contain NULL characters (ASCII 0) but it contains a space (ASCII 32).
So strlen continues past your array. It happens to exist a NULL character at position 6 (two characters after the end of the array in memory), so string length is 6. Subsequent executions of this function could return different values, as memory content outside the array is undefined. It may also crash.
This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 6 years ago.
Even though the name of the string signifies address of the first element in the string,when I perform this:
char str[]="dog";
cout<<str<<endl;
How come the whole string gets printed?
In C++, the "<<" operator is "smart". It knows the types of the thing to its left and to its right, and if the thing to its right is a character pointer and the thing to its left is an output stream, it prints the string rather than the value of the pointer.
In C, you have to tell printf() which one to do with "%p" or "%s", but "<<" makes that choice for you.
Google "C++ operator overloading"
This question already has answers here:
Get the last element of a std::string
(4 answers)
Closed 7 years ago.
In python you can say print "String"[-1] and it would print be the last character, 'g'. Is there an equivalent for this in c++?
You can use string.back() to get a reference to the last character in the string. The last character of the string is the first character in the reversed string, so string.rbegin() will give you an iterator to the last character.
Use the back() function for std::string:
std::string str ("Some string");
cout << str.back()
Output:
g
For C strings, it is
String[strlen(String) - 1];
For C++ style strings, it is either
String.back();
*String.rbegin();
String[String.length() - 1];
You can use the function:
my_string.back();
If you want to output it, then:
#include <iostream>
std::cout << my_string.back();
This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
How to convert a number to string and vice versa in C++
(5 answers)
Closed 10 years ago.
I have a function which accept a string parameter and I have an integer variable then I should convert it to string and then pass it to that function I used this code but as ostringstream is for I/O it doesn't work.
ostringstream ostr;
while (.....)
{
regnum++;
ostr<<regnum;
grph.addlastname(ostr.str());
}
for example it pass 12345 to function instead of 5,what should I do?
It's true - there are a lot of similar questions which solve "What's the best way to do this?" but I think that there's something to learn for the OP in the answer to the question of "Why does this not work?"
Therefore:
Your stringstream has an internal state, and during your loop you always append a new digit - but the previous ones are still in the stream! You can fix this by making the stringstream scope-local to the loop, i.e. declaring it inside the loop rather than outside of it.
(std::to_string is still the better solution for this particular problem, though.)
Everything is fine except one thing,
see:
ostringstream ostr;
while (.....)
{
regnum++;
ostr<<regnum;
grph.addlastname(ostr.str());
}
Your declaring your ostr outside the while, the first time that while runs, it adds '1' to the ostr, the second time, because it's the same "ostringstream" variable, it adds '2', so your string will be '12' now...
Solution: Declare ostringstream ostr, inside your while, use std::to_string, or do a ostr.clear() every time that the while ends. (The best way si declaring your ostr inside your while)