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.
Related
The problem is simple, the code below does not work. it says Process finished with exit code -1073740940 (0xC0000374). Removing ampersand does not change anything.
int main(){
string x;
scanf("%s",&x);
cout << x;
}
scanf() with the %s format specifier reads bytes into a preallocated character array (char[]), to which you pass a pointer.
Your s is not a character array. It is a std::string, a complex object.
A std::string* is not in any way the same as a char*. Your code overwrites the memory of parts of a complex object in unpredictable ways, so you end up with a crash.
Your compiler should have warned about this, since it knows that a char* is not a std::string*, and because compilers are clever and can detect mistakes like this despite the type-unsafe nature of C library functions.
Even if this were valid via some magic compatibility layer, the string is empty.
Use I/O streams instead.
You cannot pass complex objects through the ... operator of printf/scanf. Many compilers print a warning for that.
scanf requires a pointer of type char* pointing to sufficient storage for an argument of %s. std::string is something completely different.
In C++ the iostream operators are intended for text input and output.
cin >> x;
will do the job.
You should not use scanf in C++. There are many pitfalls, you found one of them.
Another pitfall: %s at scanf is almost always undefined behavior unless you you really ensure that the source stream can only contain strings of limited size. In this case a buffer of char buffer[size]; is the right target.
In any other case you should at least restrict the size of the string to scan. E.g. use %20s and of course a matching char buffer, char buffer[21];in this case. Note the size +1.
You should use cin. But if you want to use scanf() for whatever reason and still manipulate your strings with std::string, then you can read the C-string and use it to initialize your C++ string.
#include <iostream>
#include <cstdio>
#include <string>
using std::cout;
using std::string;
int main()
{
char c_str[80];
scanf("%s", c_str);
string str(c_str);
cout << str << "\n";
}
If you want to use strings, use cin (or getline).
string s;
cin>>s; //s is now read
If you want to use scanf, you want to have a char array (and don't use &):
char text[30];
scanf("%s", text); //text is now read
You can use char[] instead of string
include <iostream>
using namespace std;
int main()
{
char tmp[101];
scanf("%100s", tmp);
cout << tmp;
}
Please help.
I have this program from here that calls a function in a header file.
#include <iostream>
#include "md5.h"
#include <string>
using namespace std;
int main(){
string x;
char* v_MD5String;
MD5 md5 ;
v_MD5String = "Hello World";
x = puts(md5.digestString(v_MD5String));
cout << x;
return 0;}
The function called:
char* digestString( char *string ){
Init() ;
Update( (unsigned char*)string, strlen(string) ) ;
Final() ;
return digestChars ;}
The above works, however when I use input from the user it compiles, but the run crashes without any errors.
In the program, this is changed:
v_MD5String = "Hello World";
to this:
cin >> v_MD5String;
What should I do to get this to work?
Thanks.
So, if I understand correctly, you have the following function declared in a header file which you cannot modify:
char* digestString( char *string );
You should first know that this is questionable coding style. The function takes a char * rather than a char const *, which implies that the passed data is changed, yet it also returns something. I had to dig around in the implementation posted on the page you linked to find out that string is really an input parameter, so that the author just forgot about using const and the data is not going to be changed anyway.
(The data not going to be modified is at least my assumption upon superficial code analysis and some compile tests. You should ask the author to be really sure!)
If you use this function in C++, your first task should be to provide a safer, easy-to-understand wrapper function which uses real C++ strings (the std::string class), not C strings (which happen to be completely unencapsulated pointers to characters in memory, which is fine in the C world but not in C++). You already use one std::string in your program. That's good. Now use it more:
std::string SafeDigestString(MD5 &md5, std::string const &input)
{
// the input of digestString will never be modified:
return md5.digestString(const_cast<char *>(input.c_str()));
}
Both the const & and the parameter name make it clear that we are dealing with input.
Note that I used a const_cast<char *> to pass the std::string's C-compatible data representation, which is char const *, to the digestString function. This is one of the rare cases where a const_cast is appropriate; it's also a typical one, namely making up for shortcomings with regards to const declarations in other code you have to use. If all functions in the MD5 class correctly declared their input parameters const, then no const_cast would be needed.
Also note that I just prepend every std identifier with std::, rather than having using namespace std. This is often the better, simpler, more consistent choice.
Now that we have our safe C++ mechanism in place, main becomes drastically simpler:
int main()
{
MD5 md5;
std::string result = SafeDigestString(md5, "Hello World");
std::cout << result << "\n";
}
We have laid the base to implement user input, which is best done with the std::getline function:
int main()
{
MD5 md5;
std::string input;
std::getline(std::cin, input);
std::string result = SafeDigestString(md5, input);
std::cout << result << "\n";
}
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 want to do something like this (showing what FPS im running at in my SDL game):
SDL_WM_SetCaption("FPS: " + GetTicks(&fps)/1000.f, NULL);
But Visual Studio intellisens complains that expression must have integral or enum type.
What have i done wrong?
If this really is C++, consider streams;
std::ostringstream str;
str << "FPS: " << GetTicks(&fps)/1000.;
SDL_WM_SetCaption(str.str().c_str(), NULL);
C does not support conversion of simple types (like int or float) to more complex types (like strings).
You should check the sprintf function:
char buffer[64];
sprintf("FPS: %f", GetTicks(&fps)/1000.f);
SDL_WM_SetCaption(buffer, NULL);
In C, you can do this using sprintf.
Check out this link:
http://msdn.microsoft.com/en-us/library/ybk95axf(v=vs.71).aspx
Don't use + for adding char pointers (that's what they are in C, not strings).
EDIT:
If this is C++, as per the edit, use std::string, which has the + operator overloaded. You'll still need to convert the number to a string though.
Also, it's called concatenation.
You can either use strings, or if you are already settling for the new current C++ standard, there is also std::to_string:
#include <string>
#include <iostream>
int main() {
const std::string str = "Foobar " + std::to_string(42);
std::cout << str << '\n';
}
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*'