C++ writing multiple strings from a file - c++

Quick question. I'm doing my portfolio C++ question for a uni assignment. It is standard deviation. My question is to do with reading multiple strings from a file, see text here;
Design and write a c++ program that reads a set of scores from the file scored.dat, and outputs their mean and standard deviation to cout.
I'm not going to bother with the actual equation, I have that part nearly sorted. My query is based directly on outputting the text read from the file into strings. For example, if the document had these three scores:
10
15
11
Instead of outputting the text as it is, it would put them into three strings;
Score_One (Which would be 10)
Score_Two (Which would be 15)
Score_Three (Which would be 11)
I hope I am making sense here guys. Thanks.

you need to do something like this:
int raw_score_one = 11; //you have already set this but for the sake of clarity
std::stringstream output;
output << raw_score_one;
std::string Score_One = output.str();
for each score...

Here is a solution which was just fun to write and which hardly a solution I would expect to show up. It may have some entertainment and/or educational value as well. The basic idea is that values a written as
std::cout << 10 << 15 << 11 << reset << '\n';
std::cout << 1 << 2 << 3 << reset << '\n';
To achieve this, a bit of machinery is needed but it isn't that bad, really. The code is blow:
#include <locale>
#include <iostream>
#include <algorithm>
static int index(std::ios_base::xalloc());
static std::string const names[] = { "One", "Two", "Three", "Four", "Five" };
static std::string const score("Score_");
static std::string const other(" (Which would be ");
std::ostream& reset(std::ostream& out)
{
out.iword(index) = 0;
return out;
}
struct num_put
: std::num_put<char>
{
iter_type do_put(iter_type to, std::ios_base& fmt, char_type fill,
long v) const {
to = std::copy(score.begin(), score.end(), to);
if (fmt.iword(index) < 5) {
to = std::copy(names[fmt.iword(index)].begin(),
names[fmt.iword(index)].end(), to);
++fmt.iword(index);
}
else {
throw std::runtime_error("index out of range!");
}
to = std::copy(other.begin(), other.end(), to);
to = this->std::num_put<char>::do_put(to, fmt, fill, v);
*to++ = ')';
*to++ = ' ';
return to;
}
};
int main()
{
std::cout.imbue(std::locale(std::locale(), new num_put));
std::cout << 10 << 15 << 11 << reset << '\n';
std::cout << 1 << 2 << 3 << reset << '\n';
}

Related

fatal error on std::transform c++ [duplicate]

This question already has answers here:
Why fill_n() does not work with vector.reserve()?
(3 answers)
Closed 5 years ago.
I'm trying to transform a vector of foo instances to a string but I'm having fatal error on std::transform.
Say data has the following value:
[0]
[name] = John
[size] = 3423
[1]
[name] = Joseph
[size] = 3413
Code:
struct foo {
foo(std::string n, size_t s)
: name(std::move(n)),
size(s)
{
}
std::string name;
size_t size;
};
std::string server = "1";
std::vector<std::string> output;
output.reserve(static_cast<unsigned_long>(std::distance(std::begin(data), std::end(data))));
std::transform(std::begin(data),
std::end(data),
std::begin(output),
[&, this](foo const& item){
std::ostringstream result;
data << server << ","
<< item.name << ","
<< item.size << ";";
return result.str();
});
While debugging it stops at the line
*__result = __unary_op(*_first) of tranform implementation in stl_algo.h then goes to FatalConditionHandler of catch test framework. I'm new to both catch testing and std::transform. Can someone explain what might cause the problem and how to solve it? Thanks a lot!
You've reserved space in output, but you've left its size at zero.
You then proceed to write through its begin iterator, just as if it had space to hold data.
Then everything goes "boom".
Instead of writing through std:begin(output), consider using std::back_inserter(output) as the destination iterator.
You also have one other problem: inside your lambda, you have:
std::ostringstream result;
data << server << ","
<< item.name << ","
<< item.size << ";";
return result.str();
This looks like a fairly obvious mistake--you undoubtedly intended:
std::ostringstream result;
result << server << ","
<< item.name << ","
<< item.size << ";";
return result.str();
Personally, I'd probably structure the code somewhat differently. I'd add something like:
struct foo {
std::string name;
size_t size;
// new addition:
friend std::ostream &operator<<(std::ostream &os, foo const &f) {
return os << f.name << ',' << f.size;
}
};
...then the lambda in your transform becomes rather simpler:
std::ostringstream result;
result << server << "," item;
return result.str();
It might, however, be worth considering doing this without the stringstream itermediaries at all. In this case, you really just need string concatenation, and they impose quite a bit of overhead to do that.
struct foo {
// ...
std::string to_string() {
return name + "," + size;
}
};
Then the lambda body becomes:
return server + "," + item.to_string();
Shorter, simpler, and almost certainly faster.

Passing several datatypes from a function to main to create a class using pointers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I would like to start this thread by thanking you for taking to the time to read my query.
I have created a function called retreiveFile which as you would expects retreives a file and reads from it. The text it reads is a set of numbers and text which represent names, cost and that sort of thing.
I have used istringstream to read through the file, determine the starting number(so I know what the line represents(property, card, ect)). Currently I have the file outputting the text but only with its corresponding data.
Example:
9 Oakmoor Road 80 5 0
9 Eldon Road 50 5 0
I need to know how I could pass this information into a class as I assume because I am going to have many objects of the same class I need to pass the data into main somehow.
(I tried creating the class using constructor within the function but it would not work)
I am assuming I would have to create pointers for the information, pass it to main, create the constructors and then delete the pointers.
My question to you would be how could I do this efficiently as I need to create around 30 objects which could fit in several different types of classes as some have different parameters.
I'm sorry in advance in some information seems vague or confusing I am still, in my head, trying to picture how I could do it.
An example of one of the ways I've separated the text within the file so I can easily pass it over to its correct class.
if (word[i].find("1") == 0){ //starts with 1
istringstream is(word[i]);
string aword;
int loopTimes = 0;
while (is >> aword) { // read each word from line
string propertyArray[6];
if (loopTimes == 0){
string stringIdentificationNum = aword;
/* const char * charIdentificationNum = stringIdentificationNum.c_str();
int identificationNum = atoi(charIdentificationNum); */
cout << "(1.1)" << aword;
propertyArray[0] = aword;
}
else if (loopTimes == 1){
cout << "(1.2)" << aword;
propertyArray[1] = aword;
}
else if (loopTimes == 2){
cout << "(1.3)" << aword;
propertyArray[2] = aword;
}
else if (loopTimes == 3){
cout << "(1.4)" << aword;
propertyArray[3] = aword;
}
else if (loopTimes == 4){
cout << "(1.5)" << aword;
propertyArray[4] = aword;
}
else if (loopTimes == 5){
cout << "(1.6)" << aword << endl;
propertyArray[5] = aword;
}
loopTimes++;
/* Property(propertyArray[0], propertyArray[1], propertyArray[2], propertyArray[3], propertyArray[4], propertyArray[5]); */
}
}
An example of the propertyClass
class Property : public Card{
private:
int identificationNum;
string propertyName;
int propertyCost;
int propertyRent;
int propertyColour;
public:
//constructor
Property::Property(int inputIdentificationNum, string inputFName, string inputSName, int inputCost, int inputPropertyRent, int inputPropertyColour){
setIdentificationNum(inputIdentificationNum);
setFirstName(inputFName, inputSName);
setPropertyCost(inputCost);
setPropertyRent(inputPropertyRent);
setPropertyColour(inputPropertyColour);
cout << "Property Created" << endl;
}
//set data
void setIdentificationNum(int inputIdentificationNum){
identificationNum = inputIdentificationNum;
}
void setFirstName(string inputFName, string inputSName){
string nameCombined = inputFName + " " + inputSName;
propertyName = nameCombined;
}
void setPropertyCost(int inputCost){
propertyCost = inputCost;
}
void setPropertyRent(int inputPropertyRent){
propertyRent = inputPropertyRent;
}
void setPropertyColour(int inputPropertyColour){
propertyColour = inputPropertyColour;
}
//retreive data
int getIdentificationNum() {
return identificationNum;
}
string getName(){
return propertyName;
}
int getPropertyCost(){
return propertyCost;
}
int getPropertyRent(){
return propertyRent;
}
int getPropertyColour(){
return propertyColour;
}
};
Thank you in advance for reading this thread.
Passing pointers around is unnecessary for this task and is actually frowned on. An objects data should stay locked up and hidden in the object unless you have a really good reason to expose it. In this case OP doesn't.
What follows cleans up OP's code and fixes some of the problems that made their attempt unworkable and probably lead them down the road to over-complicating things further.
Example is a container for a list of properties. Rather than passing around pointers to to the properties, OP can pass around references to Example and read the properties from example. This allows Example to defend itself from its clients. With a pointer to a property, a client could mistakenly change change a value that could result in breaking Example or another client of Example. With a Getter method, Example can control access to the properties with whatever grain is required.
Example, in this case, allows everyone to see properties, so long as the property exists, but does not allow changing the property.
#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
class Example
{
private:
static constexpr size_t MAX_PROPERTIES = 6;
std::string propertyArray[MAX_PROPERTIES];
propertyArray is now a member variable and has scope that matches the object. Consider using a vector. It is not arbitrarily limited in size
public:
Example(std::stringstream & is)
{
std::string aword;
size_t looptimes = 0;
while (is >> aword && looptimes < MAX_PROPERTIES)
{
std::cout << "(1." << looptimes + 1 << ")" << aword << std::endl;
propertyArray[looptimes] = aword;
looptimes++;
This is where making propertyArray a vector really helps. You can use the push_back method to keep adding more and more properties. If you have a case with 8 properties in the future, it uses the exact same code as the 8 property version and you don't have to guard against overflow with the && looptimes < 6 in the while
}
}
std::string getProperty(size_t propertyNo)
New method used to get the properties for clients of Example. That way you don't have to pass around pointers to Example's data. Just pass around Example and if Example wants to give data, it can. No one can use an unprotected back door into Example to screw with Example's data without permission.
{
if (propertyNo < MAX_PROPERTIES)
{
return propertyArray[propertyNo];
}
throw std::out_of_range("Invalid property number");
}
};
And to test it out...
int main()
{
std::stringstream is ("A B C D E F G");
Example test(is);
try
{
std::cout << test.getProperty(4) << std::endl;
std::cout << test.getProperty(6) << std::endl;
}
catch (std::out_of_range & exc)
{
std::cout << exc.what() << std::endl;
}
}
Output:
(1.1)A
(1.2)B
(1.3)C
(1.4)D
(1.5)E
(1.6)F
E
Invalid property number
And now with a std::vector:
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
class Example
{
private:
std::vector<std::string> propertyArray;
public:
Example(std::stringstream & is)
{
std::string aword;
while (is >> aword)
{
propertyArray.push_back(aword);
std::cout << "(1." << propertyArray.size() << ")" << aword << std::endl;
}
}
std::string getProperty(size_t propertyNo)
{
if (propertyNo < propertyArray.size())
{
return propertyArray[propertyNo];
}
throw std::out_of_range("Invalid property number");
}
};
int main()
{
std::stringstream is ("A B C D E F G");
Example test(is);
try
{
std::cout << test.getProperty(4) << std::endl;
std::cout << test.getProperty(7) << std::endl;
}
catch (std::out_of_range & exc)
{
std::cout << exc.what() << std::endl;
}
}
Output:
(1.1)A
(1.2)B
(1.3)C
(1.4)D
(1.5)E
(1.6)F
(1.7)G
E
Invalid property number

Structured output

I recently started programming in c++ and I've bumped into a small problem. If I want my output to be structured (let's say that every line starts with a name and then a number) in a way that the names are written normally to the screen (every first letter of every name starts at the beginning of each new line) and I want the numbers that follow to be lined up in a column, how would I do this? I want the programs output to look like this:
Gary 0
LongName 0
VerylongName 0
I want my program to print something in the way above, but with different lengths of names (and the '0' in this case, lined up in a column).
Try the following: if you know the maximum length of all the names you intend to print (e.g. 20), then use the C++ i/o manipulators to set the width of the output (and left-justification). This will force the output to take up max characters.
Code snippet:
#include <iostream>
#include <iomanip>
...
// for each entry
std::cout << std::setw(20) << std::left << "Gary" << 10 << "\n";
...
std::cout << std::flush;
Here's some more information...
I'm shooting in the dark here since you haven't really included much information... HOWEVER one way you can do this is to make sure that you create the columns with padding around the name - and not worry about the numbers. Formatted output is one case where C has an advantage over C++ (IMHO). In C++ you can also do this with something like this:
cout << setw(15) << name << number << "\n";
Bonus points if you figure out ahead of time the maximum length of the name you have and add, say, 4 to it.
Not in the C++ standard library, but still worth mentioning: boost::format. It will let you write printf-like format strings while still being type-safe.
Example:
#include <boost/format.hpp>
#include <iostream>
#include <string>
struct PersonData
{
std::string name;
int age;
};
PersonData persons[] =
{
{"Gary", 1},
{"Whitney", 12},
{"Josephine ", 101}
};
int main(void)
{
for (auto person : persons)
{
std::cout << boost::format("%-20s %5i") % person.name % person.age << std::endl;
}
return 0;
}
Outputs:
Gary 1
Whitney 12
Josephine 101
struct X
{
const char *s;
int num;
} tab[] = {
{"Gary",1},
{"LongName",23},
{"VeryLongName",456}
};
int main(void)
{
for (int i = 0; i < sizeof(tab) / sizeof(struct X); i++ )
{
// C like - example width 20chars
//printf( "%-20s %5i\n", tab[i].s, tab[i].num );
// C++ like
std::cout << std::setw(20) << std::left << tab[i].s << std::setw(5) << std::right << tab[i].num << std::endl;
}
getchar();
return 0;
}

How to print a bunch of integers with the same formatting?

I would like to print a bunch of integers on 2 fields with '0' as fill character. I can do it but it leads to code duplication. How should I change the code so that the code duplication can be factored out?
#include <ctime>
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
string timestamp() {
time_t now = time(0);
tm t = *localtime(&now);
ostringstream ss;
t.tm_mday = 9; // cheat a little to test it
t.tm_hour = 8;
ss << (t.tm_year+1900)
<< setw(2) << setfill('0') << (t.tm_mon+1) // Code duplication
<< setw(2) << setfill('0') << t.tm_mday
<< setw(2) << setfill('0') << t.tm_hour
<< setw(2) << setfill('0') << t.tm_min
<< setw(2) << setfill('0') << t.tm_sec;
return ss.str();
}
int main() {
cout << timestamp() << endl;
return 0;
}
I have tried
std::ostream& operator<<(std::ostream& s, int i) {
return s << std::setw(2) << std::setfill('0') << i;
}
but it did not work, the operator<< calls are ambigous.
EDIT I got 4 awesome answers and I picked the one that is perhaps the simplest and the most generic one (that is, doesn't assume that we are dealing with timestamps). For the actual problem, I will probably use std::put_time or strftime though.
In C++20 you'll be able to do this with std::format in a less verbose way:
ss << std::format("{}{:02}{:02}{:02}{:02}{:02}",
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
and it's even easier with the {fmt} library that supports tm formatting directly:
auto s = fmt::format("{:%Y%m%d%H%M%S}", t);
You need a proxy for your string stream like this:
struct stream{
std::ostringstream ss;
stream& operator<<(int i){
ss << std::setw(2) << std::setfill('0') << i;
return *this; // See Note below
}
};
Then your formatting code will just be this:
stream ss;
ss << (t.tm_year+1900)
<< (t.tm_mon+1)
<< t.tm_mday
<< t.tm_hour
<< t.tm_min
<< t.tm_sec;
return ss.ss.str();
ps. Note the general format of my stream::operator<<() which does its work first, then returns something.
The "obvious" solution is to use a manipulator to install a custom std::num_put<char> facet which just formats ints as desired.
The above statement may be a bit cryptic although it entirely describes the solution. Below is the code to actually implement the logic. The first ingredient is a special std::num_put<char> facet which is just a class derived from std::num_put<char> and overriding one of its virtual functions. The used facet is a filtering facet which looks at a flag stored with the stream (using iword()) to determine whether it should change the behavior or not. Here is the code:
class num_put
: public std::num_put<char>
{
std::locale loc_;
static int index() {
static int rc(std::ios_base::xalloc());
return rc;
}
friend std::ostream& twodigits(std::ostream&);
friend std::ostream& notwodigits(std::ostream&);
public:
num_put(std::locale loc): loc_(loc) {}
iter_type do_put(iter_type to, std::ios_base& fmt,
char fill, long value) const {
if (fmt.iword(index())) {
fmt.width(2);
return std::use_facet<std::num_put<char> >(this->loc_)
.put(to, fmt, '0', value);
}
else {
return std::use_facet<std::num_put<char> >(this->loc_)
.put(to, fmt, fill, value);
}
}
};
The main part is the do_put() member function which decides how the value needs to be formatted: If the flag in fmt.iword(index()) is non-zero, it sets the width to 2 and calls the formatting function with a fill character of 0. The width is going to be reset anyway and the fill character doesn't get stored with the stream, i.e., there is no need for any clean-up.
Normally, the code would probably live in a separate translation unit and it wouldn't be declared in a header. The only functions really declared in a header would be twodigits() and notwodigits() which are made friends in this case to provide access to the index() member function. The index() member function just allocates an index usable with std::ios_base::iword() when called the time and it then just returns this index. The manipulators twodigits() and notwodigits() primarily set this index. If the num_put facet isn't installed for the stream twodigits() also installs the facet:
std::ostream& twodigits(std::ostream& out)
{
if (!dynamic_cast<num_put const*>(
&std::use_facet<std::num_put<char> >(out.getloc()))) {
out.imbue(std::locale(out.getloc(), new num_put(out.getloc())));
}
out.iword(num_put::index()) = true;
return out;
}
std::ostream& notwodigits(std::ostream& out)
{
out.iword(num_put::index()) = false;
return out;
}
The twodigits() manipulator allocates the num_put facet using new num_put(out.getloc()). It doesn't require any clean-up because installing a facet in a std::locale object does the necessary clean-up. The original std::locale of the stream is accessed using out.getloc(). It is changed by the facet. In theory the notwodigits could restore the original std::locale instead of using a flag. However, imbue() can be a relatively expensive operation and using a flag should be a lot cheaper. Of course, if there are lots of similar formatting flags, things may become different...
To demonstrate the use of the manipulators there is a simple test program below. It sets up the formatting flag twodigits twice to verify that facet is only created once (it would be a bit silly to create a chain of std::locales to pass through the formatting:
int main()
{
std::cout << "some-int='" << 1 << "' "
<< twodigits << '\n'
<< "two-digits1='" << 1 << "' "
<< "two-digits2='" << 2 << "' "
<< "two-digits3='" << 3 << "' "
<< notwodigits << '\n'
<< "some-int='" << 1 << "' "
<< twodigits << '\n'
<< "two-digits4='" << 4 << "' "
<< '\n';
}
Besides formatting integers with std::setw / std::setfill or ios_base::width / basic_ios::fill, if you want to format a date/time object you may want to consider using std::put_time / std::gettime
For convenient output formatting you may use boost::format() with sprintf-like formatting options:
#include <boost/format.hpp>
#include <iostream>
int main() {
int i1 = 1, i2 = 10, i3 = 100;
std::cout << boost::format("%03i %03i %03i\n") % i1 % i2 % i3;
// output is: 001 010 100
}
Little code duplication, additional implementation effort is marginal.
If all you want to do is output formatting of your timestamp, you should obviously use strftime(). That's what it's made for:
#include <ctime>
#include <iostream>
std::string timestamp() {
char buf[20];
const char fmt[] = "%Y%m%d%H%M%S";
time_t now = time(0);
strftime(buf, sizeof(buf), fmt, localtime(&now));
return buf;
}
int main() {
std::cout << timestamp() << std::endl;
}
operator<<(std::ostream& s, int i) is "ambiguous" because such a function already exists.
All you need to do is give that function a signature that doesn't conflict.

How do you append an int to a string in C++? [duplicate]

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 6 years ago.
int i = 4;
string text = "Player ";
cout << (text + i);
I'd like it to print Player 4.
The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?
With C++11, you can write:
#include <string> // to use std::string, std::to_string() and "+" operator acting on strings
int i = 4;
std::string text = "Player ";
text += std::to_string(i);
Well, if you use cout you can just write the integer directly to it, as in
std::cout << text << i;
The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
Alternatively, you can just convert the integer and append it to the string.
oss << i;
text += oss.str();
Finally, the Boost libraries provide boost::lexical_cast, which wraps around the stringstream conversion with a syntax like the built-in type casts.
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
This also works the other way around, i.e. to parse strings.
printf("Player %d", i);
(Downvote my answer all you like; I still hate the C++ I/O operators.)
:-P
These work for general strings (in case you do not want to output to file/console, but store for later use or something).
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
String streams
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;
For the record, you can also use a std::stringstream if you want to create the string before it's actually output.
cout << text << " " << i << endl;
Your example seems to indicate that you would like to display the a string followed by an integer, in which case:
string text = "Player: ";
int i = 4;
cout << text << i << endl;
would work fine.
But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:
#include <sstream>
#include <iostream>
using namespace std;
std::string operator+(std::string const &a, int b) {
std::ostringstream oss;
oss << a << b;
return oss.str();
}
int main() {
int i = 4;
string text = "Player: ";
cout << (text + i) << endl;
}
In fact, you can use templates to make this approach more powerful:
template <class T>
std::string operator+(std::string const &a, const T &b){
std::ostringstream oss;
oss << a << b;
return oss.str();
}
Now, as long as object b has a defined stream output, you can append it to your string (or, at least, a copy thereof).
Another possibility is Boost.Format:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
Here a small working conversion/appending example, with some code I needed before.
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}
the output will be:
/dev/video
/dev/video456
/dev/video321
/dev/video123
Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.
For the record, you could also use Qt's QString class:
#include <QtCore/QString>
int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData(); // prints "Player 4"
cout << text << i;
One method here is directly printing the output if its required in your problem.
cout << text << i;
Else, one of the safest method is to use
sprintf(count, "%d", i);
And then copy it to your "text" string .
for(k = 0; *(count + k); k++)
{
text += count[k];
}
Thus, you have your required output string
For more info on sprintf, follow:
http://www.cplusplus.com/reference/cstdio/sprintf
cout << text << i;
The << operator for ostream returns a reference to the ostream, so you can just keep chaining the << operations. That is, the above is basically the same as:
cout << text;
cout << i;
cout << "Player" << i ;
cout << text << " " << i << endl;
The easiest way I could figure this out is the following..
It will work as a single string and string array.
I am considering a string array, as it is complicated (little bit same will be followed with string).
I create a array of names and append some integer and char with it to show how easy it is to append some int and chars to string, hope it helps.
length is just to measure the size of array. If you are familiar with programming then size_t is a unsigned int
#include<iostream>
#include<string>
using namespace std;
int main() {
string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
int length = sizeof(names) / sizeof(names[0]); //give you size of array
int id;
string append[7]; //as length is 7 just for sake of storing and printing output
for (size_t i = 0; i < length; i++) {
id = rand() % 20000 + 2;
append[i] = names[i] + to_string(id);
}
for (size_t i = 0; i < length; i++) {
cout << append[i] << endl;
}
}
There are a few options, and which one you want depends on the context.
The simplest way is
std::cout << text << i;
or if you want this on a single line
std::cout << text << i << endl;
If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done.
If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following:
Player 1
Player 2
If you are unlucky you might get something like the following
Player Player 2
1
The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:
std::cout << text;
std::cout << i;
std::cout << endl;
If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:
printf("Player %d\n", i);
Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.
For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.
You also try concatenate player's number with std::string::push_back :
Example with your code:
int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;
You will see in console:
Player 4
You can use the following
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
If using Windows/MFC, and need the string for more than immediate output try:
int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);