How can I concatenate an int to a string? [duplicate] - c++

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
C++ int to string, concatenate strings [duplicate]
(6 answers)
Closed 8 years ago.
I have done a good hour or so of research, but I can't find a method that works for me that I actually understand, as I don't understand how buffers work. I've tried the to_string method, I've tried the .append() method, and obviously, a simple concatenation method.
My code:
fileLog[fileLogIndex].append(playerTurn+":"+moveColumn);
//fileLog[fileLogIndex] += playerTurn && ":" && moveColumn && ", ";
So. The purpose of this, or my idea, was to keep track of each move in a connect 4 game I wrote today. This was supposed to append each move, in the format aforementioned. PlayerTurn is stored as an int, 1 being player 1, 2 being player 2, and the moveColumn variable is the column that the user selected to drop their piece. If player 1 dropped a piece into column 4, the idea was to append "1:4, " to the variable and then write that line to a file.
As you can see, I have tried a few methods, like append, and even though you can't see, I have tried to to_string () method, but I either get an error, or "1:1" gives me a smiley face in the dos window, or a null in notepad++ when opening the file.
I don't want to use a method I don't understand, so I apologize if this is a repeat of another thread, I'm just tired of staring at this 1 line of code and getting nowhere with the methods I am trying. If I have to use a buffer to do this, fine, but can someone explain to me, in somewhat newbie terms, what each line is doing?
For the record, I am using Visual Studio 2010, and I'm 90% sure I don't have C++11, which I read somewhere is the reason to_string isn't working as expected for me..

The C++ way to do this (i.e., without using C's buffers and sprintf) that doesn't use C++11's to_string is by constructing the string using an ostringstream:
#include <sstream>
ostringstream out;
out << playerTurn << ":" << moveColumn;
fileLog[fileLogIndex] += out.str();

Related

How to approach .startswith() in C++? [duplicate]

This question already has answers here:
Check if one string is a prefix of another
(14 answers)
How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?
(23 answers)
Closed 1 year ago.
I'm new to C++, learning from books and online video tutorials. I've been trying to get the following lines of code to work, without much success. Basically, trying to find a C++ equivalent to python'a .startswith() or "in".
In python, what I'm trying to achieve would look like this:
names = ["John","Mary","Joanne","David"]
for n in names:
if n.startswith("J"):
print(n)
In javascript, the syntax would be quite similar (there are better ways of doing this, but I'm trying to keep the lines of code close to python's):
const names = ["John","Mary","Joanne","David"];
for (let n of names) {
if (n.startsWith("J")) {
console.log(n);
}
So, I assumed things would work similarly in C++, right?
vector <string> names {"John","Mary","Joanne","David"};
for (auto n: names) {
if (n[0] == "J") {
cout << n << endl;
}
As I've just started learning about pointers, I might be getting confused between types / values / addresses, apologies for this.
What's the best way to solve this please? Alternatively, how should I find a way to mimic what "in" does in python, but for C++?
names = ["John","Mary","Joanne","David"]
for n in names:
if "J" in n:
print(n)
Thanks!

dealing with stringstream in C++

i am reverting back to cpp after long years i have not been using it at all. i am trying to stay up date whilst refreshing my memories with correct practices and syntax, so i prefer the answers to be leaned towards cpp 17 onward(though 20 is not out yet).
so my situation is like this, assuming i have a stringstream object, i want to find an efficient way to convert its contents into upper/lower case. then i'll play with it(each even char in the string, etc). however, as far as i remember, unlike other programming languages, in c++ ::toupper/lower is done on chars, so i think it means i need to use std::transform on this container.
if you could regard the following questions while answering it would be great and allow me to capture multiple birds with one net, or something like this:
is it possible to do this with a for_each?
is it possible to use string_view and then refer to it to do the operations on it if i don't want to create a new string object to do the case manipulation?
are there any iterators for stringstream object? (like begin(),end() etc)
so what's the best way to do implement case change here?
is it possible to do this somehow without converting this to string, but rather manipulating it manually or is it path for trouble?
here's what i tried and failed ungracefuly with:
int main() {
std::stringstream beginnersmistake;
beginnersmistake<<"learning"<< " " << "to"<< "program" <<'\n';
std::function<std::stringstream> ttoupper = [&beginnersmistake](){
std::string stemp = beginnersmistake.str();
std::transform(stemp.begin(),stemp.end(),stemp.begin(),::toupper);
};
std::cout<<"voila! a mistake comming:" << ttoupper;
beginnersmistake.clear();
getchar();
return 0;
}
thank you very much for helping a noobie joining the site :)

Endless do while loop in C++ code? [duplicate]

This question already has answers here:
Using the scanf() function
(4 answers)
Closed 5 years ago.
char input[256];
do{
cout<<"..."; //prompt
scanf("%s",&input5); //user inputs string
if(strcmp(input5,"block")==0)
{} //if the user types block, then it finishes the loop and goes to the cout at the bottom
else if(strcmp(input5,"attack")==0)
{
cout<<"..."<<endl;
}
else if(strcmp(input5,"look")==0)
{
cout<<"..."
}
else
{
cout<<"..."<<endl;
}
}while(strcmp(input5,"block")!=0); //loop ends when block is typed
cout<<"...";
I am having issues with my do while loop. I am doing a project for school that involves a text adventure kind of game. The user is prompting how to respond to an attack. The desired command is "block", which will move the user on to the next sequence. When "block" is typed into the scanf, it endlessly loops and prints what is in the "else" condition. I don't see what the problem is and all feedback is appreciated.
I just tried your code and it works fine (though I removed the & in the scanf), and created 'input5' as a char array.
Though that aside, there's a few things that you might want to change. I'd stick to using 'cin' instead of scanf, as you're mixing C and C++. That would allow you to use a 'string' for 'input5', and compare them using the '==' operator, which is quite a bit cleaner. Maybe think of a more descriptive name than 'input5' too, as if you've got lots of 'inputX' variables then things will get messy.
Edit: I'd also refrain from "using namespace std;", as you might end up with naming collisions.
Most likely you don't need the & operator before input5 on the scanf line, because the things scanf expects for %s fields are already pointers/arrays. Although I don't see how input5 is declared, so I'm not sure if this is the (only) problem. You should have included that in the code snippet also.
EDIT: Just a note: It's not particularly elegant to mix C-style (scanf) and C++ style (cout) IO. You wouldn't have this problem with cin.
Obviously, the loop does not terminate because the string comparison does not return equality. And this must be because input5 does not contain the typed input (and for the same reason, the else clause is executed whatever the input).
As input5 is only modified by the scanf call, this must be the root of the evil. A simple debugging session would have revealed it immediately.
The reason is simple: you must pass scanf the address of the buffer, but you are actually passing the address of the address, and overwriting the value of the variable input5 (for which we don't have the declaration but can infer char* or const char*).
In a 32 bits environment, this could cause a crash by overwriting the stack. Under 64 bits, you'll need more typing to obtain it.

How to use multi words un 1 variable? [duplicate]

This question already has answers here:
std::cin input with spaces?
(8 answers)
Reading string with spaces in c++
(3 answers)
Closed 6 years ago.
I am trying to asign more than one words to a variable, at once, but after inserting space, it looks for another variable. Lets say I need to write Hello c++ world in a variable. The onliest solution I've found, is the following C++ code:
#include <iostream>
using namespace std;
int main()
{
string word1,word2,word3;
cin>>word1>>word2>>word3;
return 0;
}
Ok, but what if you dont know how much words is the sentance going to be?
Example entry:
say Hello there!
Example print: Hello there
Example entry: say This is much longer, we can't create milions of variables!
Example print: This is much longer, we can't create milions of variables!
Please help! What I need here is not only use spaces in a variable, I want before this to have another "command" like in the case above: the command say.

C++ Multi-Dimensional Array saving/loading to file error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've been working on this C++ project for roughly 2 weeks now and I'm stumped on a couple things regarding 2D Arrays. To start off here is the code I wrote as of now:
http://pastebin.com/vCsz947Q
I decided to provide this as a pastebin link due to the fact that it's rather large (it uses 8 functions) and I thought it would save space in this post. I'm new to this site so I apologize if there's a better way that I'm not aware of.
The Problem:
When I go to save my "char seating" array to a .dat file using the "save seats" function that I created, I get a file that gives me the following garbage character " Ì " instead of the intended ' # ' (for open seats) or ' * ' (if a seat is bought).
My functions will save the intended amount of rows (15) and columns (30) despite this though. Also an asterisk will be placed when I go to "purchase a seat" in this program in the file. Additionally my program loads the files as intended, except for the fact that... Well... There's garbage data stored in the seat array.
I feel like this relates to another problem I'm having where if I go to the "purchase seats" function and I say to purchase a seat, it should replace a # with a *, but it doesn't, yet in the saved file it will show an asterisk in the intended spot... Which is very strange.
I have absolutely no idea why this occurs, and what's frustrating is this one thing that's preventing me from finishing this program. I want to believe that my original array in int main that's being called by other functions isn't being updated properly, but I don't know, which is why I came here to seek assistance.
Thank you for your assistance whoever can help.
Well for a start you have some undefined behaviour here inside your displaySeatingChart (char displaySeats[ ][30], float displayPrices[ ]) function with the following:
const int rowDisplay = 15;
const int colDisplay = 30;
as later within one of your loops you have
cout << displaySeats[rowDisplay][colDisplay];
which is clearly reading beyond the array bounds since in main() you define
const int rowMain = 15;
const int colMain = 30;
char seating[rowMain][colMain];
float seatPrices[15];
and pass both seating and seatPrices to the displaySeats function. There may well be other problems with your code but this at least is a clear example of undefined behaviour. Consider stepping through the code with a debugger to get a clearer idea of the source of the issue.
On another note given that you are working with C++ consider working with std::vector instead of arrays. This will give you more scope to ascertain the dimensions of the items that arrays that you are working with from within your utility functions and result in less potential for errors in array access.