Below is a cout of a c++ statement:
cout << "TESTING" + 2 << endl;
I understand why this statement will print out sting. But the question I have is if I do the code below it will cause an error. I don't understand why as this is the same thing. Sorry for a basic question I am new to c++.
string t = "TESTING";
cout << t + 2 << endl;
Thanks in advance for any help. :)
This is an interesting case. I'm not sure if you've actually printed the result of your first statement or not, but if you do you see that you are actually getting "STING" and not "TESTING2", or something like that!
There are a few things going on here. In your first statement, you are constructing a string using a string literal. In this case, C++ create a const char[N] and put your string into it. Since char[N] is technically an array (and array is a pointer), the operator + acts as increment and the result of "TESTING" + 2 is actually a pointer to the second element of "TESTING", which is "STING". You'll not see any errors, because C++ thinks that what's you wanted to do.
In your second statement, you are telling C++ that I want a std::string object. The std::string is by design safer and will nag at you if you try to add anything other than a string to it. So, when you do, you get an error. For your second statement to work as intended, you should write t + std::to_string(2).
It is important to know the difference between string and char types. String is a class that manages string of characters. And char[] is an array of characters. Refer this question for the explanation. In your case the code will work if you do:
#include <iostream>
int main ()
{
char t[] = "TESTING";
std::cout << t + 2 << std::endl;
return 0;
}
If you want to concatenate string with int then you should explicitly convert it:
#include <iostream>
int main ()
{
std::string m = "Testing ";
std::cout << m + std::to_string(2) << std::endl;
return 0;
}
Related
So, the goal of this function is for the user to give a array of strings, then using a previously defined function, determine if each individual string is a valid sentence. Unfortunately, I am completely lost about how to go about this.
int validSentences(const std::vector<std::string> paragraph)
{
char* str;
for (auto a : paragraph)
{
std::cout << a << " ";
strcat(str, a.c_str);
}
std::cout << str << std::endl;
}
Here is what I have as a prototype, but I'm sure this is way off base.
I think a good start to my question would be this:
How would I go about taking each string within the given vector, and converting it to a cstring using an enhanced for loop that utilizes the auto keyword?
I have been working in Java since I started programming and decided to learn c++.
What I wrote in Java looked like this:
showMessage("Hello world" + randomNumber);
And it showed text + integer or float or whatever. But it wont work in c++.
Error message by xCode: Invalid operands to binary expression ('const char *' and 'float')
Cheers!
You can do a sprintf according to Anton, or to be more c++:
std::stringstream ss;
ss << "Hello, world " << randomNumber;
showmessage(ss.str());
(there's nothing wrong with sprintf, especially if you use snprintf instead).
ostringstream os;
os<<"HelloWorld"<<randomnumber;
string s;
s = os.str();
string s now contains the string you want as a string object.
Also you can use boost::lexical_cast to cast numbers into strings which is fastest method in most cases:
showMessage("Hello world" + boost::lexical_cast<std::string>(randomNumber));
showMessage declaration is
void showMessage(cosnt std::string& message)
Consider adding a new function that is able to convert several types to std::string:
template<typename ty>
string to_str(ty t)
{
stringstream ss; ss << t;
return ss.str();
}
Usage:
"Hello World " + to_str(123)
Define a class S. Then write
showMessage( S() << "Hello world" << randomNumber );
I've coded up the S class too many times for SO, and it's a good exercise to create it, hence, not providing the source code.
Note that you can reasonably call it StringWriter or something like that, and then just use a typedef for more concise code in function calls.
I am not sure if c-style answer is fine, but I have already answer it here in a cocos2d-x question.
Trying to set up a CCLabelTTF with an integer as part of it's string in Cocos2d-X C++
With C++11:
showMessage("Hello world" + std::to_string(randomNumber));
you should print into the char* instead.
You could do something like
char* tempBuffer = new char[256];
sprintf_s(tempBuffer, 256, "Hello world %d", randomNumber);
showMessage(tempBuffer);
In C++ the standard way to concatenate strings and primitives is to use stringstream. Which fulfils the same functionality (and a little bit more) as StringBuilder in Java (of course its API differs). However, if you are comfortable using cout then you should be fine.
eg.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main () {
stringstream ss;
ss << "Some string - " << 124; // build string
string str = ss.str(); // extract string
cout << str << endl;
return 0;
}
Quick reference for stringstream http://www.cplusplus.com/reference/iostream/stringstream/stringstream/
I am trying to build my overall expertise in C++ coming from VBA, so please forgive any glaring issues with my code... Using this simple program below, I am getting unexpected output.
#include <iostream>
int main() {
char f[]="", c[]="";
std::cin >> f;
std::cout << f << std::endl;
std::cin >> c;
std::cout << f << std::endl;
return 0;
}
When run, this is my result:
ABC (input)
f - ABC (output)
DEF (input)
f - EF (output)
Also tried as:
ABC DEF (input)
f - ABC (output)
f - EF (output)
I would expect that the output would be the same for both lines, since I THINK I'm only reading into f once. Moreover, if I am taking the cin and applying it to f, why does the first attempt read the entire string (ABC) while the second attempt is missing the D?
I tried also printing the result using this code, but the same problem occurs, so I'm assuming here that it's a problem with the cin and not cout.
for (j=0;j<3;j++) {
std::cout << f[j];
}
std::cout << std::endl;
Doing some research, I found this question, which looked promising, but when I changed my declaration from char f[] to char *f, I ended up with SEGFAULTs on the cin, while const char *f wouldn't even compile.
I am fumbling blindly here and would appreciate some guidance on how to correctly use cin and/or char arrays.
To reiterate my question: Why does the output std::cout << f << std::endl;, while not explicitly reassigning a value, vary in this way?
char f[]="", c[]="";
is equivalent to
char f[1]="", c[1]="";
i.e. it declares both f and c as arrays of one character (namely NUL or \0, the null terminator).
In other words, you're reading into both arrays past their end, which could work perfectly, could do very strange things (like you're seeing), could crash, or could make purple elephants erupt from your monitor next Tuesday.
It looks like you should use the getline function. There are two versions of it...
One is in the C++ standard library and is used this way:
std::string s;
// the following returns the stream that you give
// (the cast is non-functional, it's there to show the type)
(istream&)getline(cin, s);
The string object is nice for this because it dynamically sizes itself to hold whatever you receive.
The other getline is in the standard C library, at least on Mac OS X (run man 3 getline for more) and it uses FILE* instead of streams. That version is capable of dynamically reallocating a char array if you want it to, but you don't have to use it that way.
#include < iostream >
int main() {
char f[]="";
char c[]="";
Try these, it solve the problem for me ;D
I'm trying to figure out how to print a string several times. I'm getting errors. I just tried the line:
cout<<"This is a string. "*2;
I expected the output: "This is a string. This is a string.", but I didn't get that. Is there anything wrong with this line? If not, here's the entire program:
#include <iostream>
using namespace std;
int main()
{
cout<<"This is a string. "*2;
cin.get();
return 0;
}
My compiler isn't open because I am doing virus scans, so I can't give the error message. But given the relative simplicity of this code for this website, I'm hoping someone will know if I am doing anything wrong by simply looking.
Thank you for your feedback.
If you switch to std::string, you can define this operation yourself:
std::string operator*(std::string const &s, size_t n)
{
std::string r; // empty string
r.reserve(n * s.size());
for (size_t i=0; i<n; i++)
r += s;
return r;
}
If you try
std::cout << (std::string("foo") * 3) << std::endl
you'll find it prints foofoofoo. (But "foo" * 3 is still not permitted.)
There is an operator+() defined for std::string, so that string + string gives stringstring, but there is no operator*().
You could do:
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string str = "This is a string. ";
cout << str+str;
cin.get();
return 0;
}
As the other answers pointed there's no multiplication operation defined for strings in C++ regardless of their 'flavor' (char arrays or std::string). So you're left with implementing it yourself.
One of the simplest solutions available is to use the std::fill_n algorithm:
#include <iostream> // for std::cout & std::endl
#include <sstream> // for std::stringstream
#include <algorithm> // for std::fill_n
#include <iterator> // for std::ostream_iterator
// if you just need to write it to std::cout
std::fill_n( std::ostream_iterator< const char* >( std::cout ), 2, "This is a string. " );
std::cout << std::endl;
// if you need the result as a std::string (directly)
// or a const char* (via std::string' c_str())
std::stringstream ss;
std::fill_n( std::ostream_iterator< const char* >( ss ), 2, "This is a string. " );
std::cout << ss.str();
std::cout << std::endl;
Indeed, your code is wrong.
C++ compilers treat a sequence of characters enclosed in " as a array of characters (which can be multibyte or singlebyte, depending on your compiler and configuration).
So, your code is the same as:
char str[19] = "This is a string. ";
cout<<str * 2;
Now, if you check the second line of the above snippet, you'll clearly spot something wrong. Is this code multiplying an array by two? should pop in your mind. What is the definition of multiplying an array by two? None good.
Furthermore, usually when dealing with arrays, C++ compilers treat the array variable as a pointer to the first address of the array. So:
char str[19] = "This is a string. ";
cout<<0xFF001234 * 2;
Which may or may not compile. If it does, you code will output a number which is the double of the address of your array in memory.
That's not to say you simply can't multiply a string. You can't multiply C++ strings, but you can, with OOP, create your own string that support multiplication. The reason you will need to do that yourself is that even std strings (std::string) doesn't have a definition for multiplication. After all, we could argue that a string multiplication could do different things than your expected behavior.
In fact, if need be, I'd write a member function that duplicated my string, which would have a more friendly name that would inform and reader of its purpose. Using non-standard ways to do a certain thing will ultimately lead to unreadable code.
Well, ideally, you would use a loop to do that in C++. Check for/while/do-while methods.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int count;
for (count = 0; count < 5; count++)
{
//repeating this 5 times
cout << "This is a string. ";
}
return 0;
}
Outputs:
This is a string. This is a string. This is a string. This is a string. This is a string.
Hey there, I'm not sure that that would compile. (I know that would not be valid in c# without a cast, and even then you still would not receive the desired output.)
Here would be a good example of what you are trying to accomplish. The OP is using a char instead of a string, but will essentially function the same with a string.
Give this a whirl:
Multiply char by integer (c++)
cout<<"This is a string. "*2;
you want to twice your output. Compiler is machine not a human. It understanding like expression and your expression is wrong and generate an error .
error: invalid operands of types
'const char [20]' and 'int' to binary
'operator*'
I'm new to C++. I want to make a char*, but I don't know how.
In Java is it just this:
int player = 0;
int cpu = 0;
String s = "You: " + player + " CPU: " + cpu;
How can I do this? I need a char*.
I'm focusing on pasting the integer after the string.
You almost certainly don't want to deal with char * if you can help it - you need the C++ std::string class:
#include <string>
..
string name = "fred";
or the related stringstream class:
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
int player = 0;
int cpu = 0;
ostringstream os;
os << "You: " << player << " CPU: " << cpu;
string s = os.str();
cout << s << endl;
}
if you really need a character pointer (and you haven't said why you think you do), you can get one from a string by using its c_str() member function.
All this should be covered by any introductory C++ text book. If you haven't already bought one, get Accelerated C++. You cannot learn C++ from internet resources alone.
If you're working with C++, just use std::string. If you're working with char*, you probably want to work with C directly. In case of C, you can use the sprintf function:
char* s = // initialized properly
sprintf( s, "You: %d CPU: %d", player, cpu );
Just call s.c_str( );.Here you you can see more.
PS. You can use strcpy to copy the content to new variable and then you will be able to change it.
char * means "pointer to a character".
You can create a pointer to a 'string' like this:
char* myString = "My long string";
Alternatively you can use std::string:
std::string myStdString("Another long string");
const char* myStdString.c_str();
Notice the const at the beginning of the last example. This means you can't change the chars that are pointed to. You can do the same with the first example:
const char* = "My long string";
Consider using stringstreams:
#include <iostream>
#include <sstream>
using namespace std;
int main ()
{
int i = 10;
stringstream t;
t << "test " << i;
cout << t.str();
}
It probably would have been for the best if C++ had overloaded the "+" operator like you show. Sadly, they didn't (you can though, if you want to).
There are basicly three methods for converting integer variables to strings in C++; two inherited from C and one new one for C++.
The itoa() routine. This is actually non-standard, but most compilers have it. The nice thing about it is that it returns a pointer to the string, so it can be used in functional-style programming.
sprintf(). The second holdover from C, this routine takes a destination string, a format string, and a list of parameters. How many parameters there are, and how they are interpreted depend on how the "format" string parses. This makes sprintf both immensely powerful and immensely dangerous. If you use this approach, I can pretty much guarantee you will have crash bugs your first few tries.
std::ostringstream. The C++ way. This has pretty much all the power of sprintf(), but is much safer. The drawback here is that you have to declare it, and it is not a string, so you still have to convert it to one when you are done. That means at least three lines of code are required to do anything with an ostringstream. It is also really ugly, particularly if you try any special formatting.