In C++, I thought you could do "string times 2" = stringstring? - c++

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*'

Related

cout operator << doesn't work for vector<char> [duplicate]

This question already has answers here:
How do I print out the contents of a vector?
(31 answers)
Closed 1 year ago.
Why doesn't this vector print out?
void str_read(std::vector<char> str);
int main() {
std::vector<char> str;
str_read(str);
std::cout << str << std::endl;
return -1;
}
void str_read(std::vector<char> str) {
while (1) {
char ch;
scanf("%c", &ch);
if (ch == '\n');
break;
}
}
I get an error:
error: no type named 'type' in 'struct std::enable_if<false, void>'
You get the error because there is no standard operator<< defined for std::vector. If you want that, you have to implement it yourself.
Even so, str_read() takes in a std::vector by value, so it receives a copy of the caller's vector, and thus any modifications it makes will be to that copy and thus lost when str_read() exits. That means the vector in main() is never populated.
Try this instead:
#include <iostream>
#include <vector>
#include <string>
std::ostream operator<<(std::ostream &out, const std::vector<char> &vec) {
for(auto ch : vec) {
out << ch;
}
return out;
/* alternatively:
return out.write(vec.data(), vec.size());
*/
}
void str_read(std::vector<char> &str) {
char ch;
while (cin.get(ch) && ch != '\n') {
str.push_back(ch);
}
}
int main() {
std::vector<char> str;
str_read(str);
std::cout << str << std::endl;
}
That being said, why not just use std::string instead of std::vector<char>? There is a standard operator<< defined for std::string, and a standard std::getline() function for reading characters into std::string until '\n':
#include <iostream>
#include <string>
int main() {
std::string str;
std::getline(cin, str);
std::cout << str << std::endl;
}
There are 3 BIG problems here.
You are passing the vector by value, not by reference. As a result, any changes made to the vector in the function will stay local to the vector initialised as a part of that function call stack. It will be deleted by the time you return. so change the signature to str_read(std::vector<char>& str).
You are going through the stdin capture character by character. AFAIK scanf although will read the new line character, will leave it in the buffer not appending it to your string. From the looks of it, all you are trying to do is read a string from stdin, store it in a char array, and print that char array out. Don't overengineer stuff. just use std::cin and store it in a string, to begin with, like
std::string captured_string;
std::getline(std::cin, captured_string);
You can then std:cout << captured_string << "\n"; directly
If you insist on storing characters in a vector, which I do not understand why would you need to, you can just do std::vector<uint8_t> char_array(captured_string.begin(), captured_string.end()). However, std::cout << char_array << "\n" will still not work. That is for 2 reasons, the first one being that std::vector<T, allocator> does not have an overload for << of std::ostream. The second is that the moment you convert your string to an array of characters, they do not mean the same thing.
I think you misunderstood what you were taught in class about strings being stored as arrays of characters. They are indeed stored as arrays, but an array type and a string type are fundamentally different and are not equivalent.
Capturing the string from stdin will anyway store it in a char* or a std::string as I have shown above. You can use that directly without having to convert a string to an array of characters.
In essence, your program decays to this
#include <iostream>
#include <string>
int main()
{
std::string captured_string;
std::getline(std::cin, captured_string);
std::cout << captured_string << "\n";
return EXIT_SUCCESS;
}
EDIT
I just realised that your objective may have been to print the string character by character. In that case, you don't need to convert it to an array. There are multiple ways of doing this, but the least confusing and probably the easiest way of doing this would be to use the range-based for loop.
int main()
{
std::string captured_string;
std::getline(std::cin, captured_string);
for (auto& ch: captured_string) // containers in the standard library support range based for loops.
std::cout << ch << "\n"; // print each character in the string on a new line
return EXIT_SUCCESS;
}
First, explain
error: no type named 'type' in 'struct std::enable_if<false, void>'
cout is character-oriented stream output and does not accept output formats of the vector<char> type.
Vector is an array of elements of the specified type. If you want to use a vector, you can store values in it first:
vector<char> str;
str.push_back('H');
An element of the array is then printed to standard output cout
cout << str[0] <<endl;
The second problem is that your function str_read is defined as void, which has no value, so it cannot be located in cout's standard output either.
It looks like you want to put the characters as input into a vector and print them out. If you position the function as void, you will need to change the value of str by reference
Next question, I see that your while loop break is mistimed and does not combine with if. You should not add a semicolon after an if statement.
if (ch == '\n')break;
Finally, if you choose to change the value of str by reference, you need to implement this in the function, as mentioned above, when you type a value of ch, you need to use str.push_back(ch) to store it.
Your 'str' variable doesn't have anything in it when you try to display it. You also don't initialize your vector to any variables for the function to read anyways.

C++ Adding to a string (Output)

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;
}

How to print out the first element of a const string?

How to print out the first element of a const string?
I tried to do std::cout << path[0] << std::endl; on CLion
but path[0] does not work and the IDE would warn.
CLion warns that
Cannot assign to return value because function 'operator[]' returns a const value.
type print(const std::string &path){}
You can use
std::string::at
It can be used to extract characters by characters from a given string.
Consider an example
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
string str = "goodday";
cout << str.at(0);
return 0;
}
Hope this will help you.
First of all you can ignore the warning sometimes the compiler complains about unnecessary things, secondly do not do the following:
type print(const std::string &path){}
Dangerous, first of all Passing a string as a reference?? Think about it from the compilers point of view, the string is const, each time you use the += you are actually create a new string. But if you use the & with the string you are telling the compiler that you are planning to modify the string object which has type const..... Use string path as a parameter but never, ever use string& path......

C++: How to build Strings / char*

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.

How to declare an array of strings in C++?

I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?
Possible non-solutions:
vector<string> v;
v.push_back("abc");
b.push_back("xyz");
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
Problems - no way to create the vector on one line with a list of strings
Possible non-solution 2:
string list[] = {"abc", "xyz"};
Problems - no way to get the number of strings automatically (that I know of).
There must be an easy way of doing this.
C++ 11 added initialization lists to allow the following syntax:
std::vector<std::string> v = {"Hello", "World"};
Support for this C++ 11 feature was added in at least GCC 4.4 and only in Visual Studio 2013.
You can concisely initialize a vector<string> from a statically-created char* array:
char* strarray[] = {"hey", "sup", "dogg"};
vector<string> strvector(strarray, strarray + 3);
This copies all the strings, by the way, so you use twice the memory. You can use Will Dean's suggestion to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.
Also, if you're really gung-ho about the one line thingy, you can define a variadic macro so that a single line such as DEFINE_STR_VEC(strvector, "hi", "there", "everyone"); works.
Problems - no way to get the number of strings automatically (that i know of).
There is a bog-standard way of doing this, which lots of people (including MS) define macros like arraysize for:
#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))
Declare an array of strings in C++ like this : char array_of_strings[][]
For example : char array_of_strings[200][8192];
will hold 200 strings, each string having the size 8kb or 8192 bytes.
use strcpy(line[i],tempBuffer); to put data in the array of strings.
One possiblity is to use a NULL pointer as a flag value:
const char *list[] = {"dog", "cat", NULL};
for (char **iList = list; *iList != NULL; ++iList)
{
cout << *iList;
}
You can use the begin and end functions from the Boost range library to easily find the ends of a primitive array, and unlike the macro solution, this will give a compile error instead of broken behaviour if you accidentally apply it to a pointer.
const char* array[] = { "cat", "dog", "horse" };
vector<string> vec(begin(array), end(array));
You can use Will Dean's suggestion [#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.
The case where it doesn't work is when the "array" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — some_function(string parameter[]) is really some_function(string *parameter).
Here's an example:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
int main() {
const char* const list[] = {"zip", "zam", "bam"};
const size_t len = sizeof(list) / sizeof(list[0]);
for (size_t i = 0; i < len; ++i)
std::cout << list[i] << "\n";
const std::vector<string> v(list, list + len);
std::copy(v.begin(), v.end(), std::ostream_iterator<string>(std::cout, "\n"));
}
Instead of that macro, might I suggest this one:
template<typename T, int N>
inline size_t array_size(T(&)[N])
{
return N;
}
#define ARRAY_SIZE(X) (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1)
1) We want to use a macro to make it a compile-time constant; the function call's result is not a compile-time constant.
2) However, we don't want to use a macro because the macro could be accidentally used on a pointer. The function can only be used on compile-time arrays.
So, we use the defined-ness of the function to make the macro "safe"; if the function exists (i.e. it has non-zero size) then we use the macro as above. If the function does not exist we return a bad value.
#include <boost/foreach.hpp>
const char* list[] = {"abc", "xyz"};
BOOST_FOREACH(const char* str, list)
{
cout << str << endl;
}
#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>
int main()
{
const std::vector< std::string > v = boost::assign::list_of( "abc" )( "xyz" );
std::copy(
v.begin(),
v.end(),
std::ostream_iterator< std::string >( std::cout, "\n" ) );
}
You can directly declare an array of strings like string s[100];.
Then if you want to access specific elements, you can get it directly like s[2][90]. For iteration purposes, take the size of string using the
s[i].size() function.