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"
Related
This question already has answers here:
C++ Comparison of String Literals
(8 answers)
Closed 2 years ago.
I was trying to learn about "<" operator on c++ strings and tried some test cases. I realized the two codes which I thought should behave the same was giving different results. Below are the codes, what is the reason for this?
string s="test";
string k="tes";
cout<<(s<k)<<endl; //returns false so it prints 0
cout<<("test"<"tes")<<endl; // returns true so it prints 1
(s < k) compares the values of the strings as you would expect.
("test" < "tes") compares the pointers to the beginning of the string literals as the compiler decides to arrange them in memory. Therefore, this comparison may return 0 or 1 depending on the compiler and settings in use, and both results are correct. The comparison is effectively meaningless.
The "C way" to compare these string literals would be strcmp("test", "tes").
s and k are string objects for which a comparison operator has been defined and performs what you expect.
"test" and "tes" are pointers to char that hold the address of the locations where these characters are stored. Thus the comparison is on the addresses.
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..
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:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Why can't I write to a string literal while I *can* write to a string object?
(4 answers)
Is it possible to modify a string of char in C?
(9 answers)
Closed 8 years ago.
Basically, I am trying to increment the int value of port. This should be easy but I am a little stuck.
It compile fine, but I got this error when I run it:
Access violation writing location 0x001f5834
#include "stdafx.h"
#include "iostream"
using namespace std;
#define TESTING "5002"
int main()
{
char* port = TESTING;
int portint;
sscanf ( port, "%d", &portint );
portint++;
cout << portint << endl; // it works fine up to here, it prints 5003
sprintf ( port, "%d", portint);
return 0;
}
By default, compiler treats string literals as immutable, and an attempt to modify the contents of one results in an access violation error at run time because these strings are put into code segment, and it's read only. In your case, TESTING is a string literal, you can't not change its values. Try:
char port[] = "5002";
Meanwhile, the compiler should have warning on this: when you assign a const char* type to a char* type.
MS C++ compiler has a compiler option regards this: Zc:strictStrings.
You are trying to write "5003" back into "5002". "5002" is a string literal and cannot be written to.
I'll try to find a good duplicate for this question, because it has been asked in many ways, many times.
In your usage, "5002" becomes a static array of characters and as such can not be modified. I believe K&R address this, but I don't have the book in front of me right now. Behavior would be different if you had declared an array.
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)