Printing out std::array with strings not working - c++

I have the following code and it is not printing out to console:
void generateRandomStringArray(array<string, N> &arrayRef)
{
cout << "Generating random string array..." << endl;
for (size_t i = 0; i < N; i++)
{
arrayRef[i] = randomString();
cout << "Value of i = " << i << ": " << stoi(arrayRef[i]) << endl;
cout << arrayRef[i] << endl;
}
cout << "Generating array successful." << endl;
};
The problem is at the line cout << arrayRef[i] << endl; and i get the error, that there is a unhandeld exception, but what is the problem? Why is the exception thrown and how can I correct this?
Exception trace:
First-chance exception at 0x76EFC42D in SortingAlgorithms.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x0344F8EC.
If there is a handler for this exception, the program may be safely continued.

Swap the lines:
cout << "Value of i = " << i << ": " << stoi(arrayRef[i]) << endl;
cout << arrayRef[i] << endl;
to
cout << arrayRef[i] << endl;
cout << "Value of i = " << i << ": " << stoi(arrayRef[i]) << endl;
and You'll see the error is at the stoi call, where you're calling stoi with some broken string.

Related

Wrong values after first cout

I'm making a test program for starting with C++ :)
It's showing wrong values after first print
This is the code (very simple)
#include "pch.h"
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
int varInt = 123456;
char varString[] = "DefaultString";
char arrChar[128] = "Long char array right there ->";
int * ptr2int;
ptr2int = &varInt;
int ** ptr2ptr;
ptr2ptr = &ptr2int;
int *** ptr2ptr2;
ptr2ptr2 = &ptr2ptr;
while(1){
cout << "Process ID: " << GetCurrentProcessId() << endl;
cout << "varInt (0x" << &varInt << ") = " << varInt << endl;
cout << "varString (0x" << &varString << ") = " << varString << endl;
cout << "varChar (0x" << &arrChar << ") = " << arrChar << endl;
cout << "ptr2int (0x" << hex << &ptr2int << ") = " << ptr2int << endl;
cout << "ptr2ptr (0x" << hex << &ptr2ptr << ") = " << ptr2ptr << endl;
cout << "ptr2ptr2 (0x" << hex << &ptr2ptr2 << ") = " << ptr2ptr2 << endl;
cout << "Press ENTER to print again." << endl;
getchar();
cout << "-----------------------------------" << endl;
}
return 0;
}
The expected results are obvious, as the code is published as is:
Process ID is integer so should return 12704 (or any int value) instead of 31a0
varInt it's also integer and should return 123456 instead of 1e240
1e240 is the same thing as 123456 in hex. The first iteration will print 123456 correctly but after you set the base flag of cout to hex mode, you need to set it back to dec to print 123456 again on the next loop.
cout << "varInt (0x" << &varInt << ") = " << dec << varInt << endl;
See here for documentation.

Accessing array pointer in Header file?

By attempting to access the TCPSocket inside my "clientArray" I get a Access Violation error. How would I access it properly?
My header file holds the TCPSocket *clientArray.
public:
TCPsocket *clientArray;
SDLNet_SocketSet aSocketSet;
bool serverOn;
It is defined within my constructor:
clientArray = new TCPsocket[maxsockets];
aSocketSet = SDLNet_AllocSocketSet(maxsockets);
It is accessible within another function of mine (it works here without issue):
void ServerSocket::waitingForConnection() {
std::cout << '\r' << flush << "Players connected: " << playersConnected << ". Listening for connection... ";
TCPsocket newsocket = SDLNet_TCP_Accept(serverSocket);
SDL_Delay(1000);
if (!newsocket){
//std::cout << '\r' << flush << "Listening for connection. ";
//std::cout << SDLNet_GetError() << std::endl;
}
else{
std::cout << '\r' << flush << "Socket (client " << slotnum + 1 << ") created successfully. " << std::endl;
clientArray[slotnum] = newsocket;
int n = SDLNet_TCP_AddSocket(aSocketSet, newsocket);
if (n < 0){
std::cout << "Client " << slotnum + 1 << " failed to connect. " << std::endl;
}
else{
char text[10];
std::cout << "Client " << slotnum + 1 << " added to client array successfully." << std::endl;
serverMessage(slotnum, "2 You are successfully connected to the server.");
std::cout << "Sent connection validation to Client " << slotnum + 1 << "." << endl;
std::cout << "Allocating player " << slotnum + 1 << " with player number ." << endl;
serverData(slotnum, '5', slotnum+1);
//ACCESSING IT HERE WITHOUT ISSUE
SDLNet_TCP_Recv(clientArray[slotnum], text, 10);
std::cout << "received text = " << text << endl;
interpretData(text);
slotnum++;
}
//SDLNet_TCP_Close(newsocket);
//SDLNet_TCP_Close(serverSocket);
//code here
}
}
However later on when I try to access it via another function, I get an Access Violation Error :
Unhandled exception at 0x00AED839 in Server.exe: 0xC0000005: Access violation reading location 0x0000000C.
I am calling the problematic function from my Game's Update function as following:
void Game::Update(){
while (g_playersConnected == 2)
{
printGrid();
serverSocket->waitForPlayer((playerTurn-1));
changeTurn();
system("pause");
}
//cout << "Game's Update is running" << endl;
};
This is my other function that is attempting to access the array :
void ServerSocket::waitForPlayer(int playerNum)
{
cout << "Waiting for player " << playerNum + 1 << " (In array : " << playerNum << ")." << endl;
char text[10];
SDLNet_TCP_Recv(clientArray[playerNum], text, 10);
std::cout << "received text = " << text << endl;
interpretData(text);
}
I have not set up Copy constructors or assignment operators and my destructors are just empty blocks at the moment.
ServerSocket::~ServerSocket(){}
Which direction should I go towards solving this issue?
All the best

GetConsoleSelectionInfo C++

cI want to select some text with my cursor using the Mark Function from Console, but my code doesn't work ...
CONSOLE_SELECTION_INFO c;
if(GetConsoleSelectionInfo(&c))
{
while((c.dwFlags & CONSOLE_MOUSE_DOWN) == 0) { if(c.dwFlags) cout << c.dwFlags; }
cout << "SelectionAnchor: " << c.dwSelectionAnchor.X << " " << c.dwSelectionAnchor.Y;
cout << "RectangleSelection: " << c.srSelection.Top << " " << c.srSelection.Left << c.srSelection.Bottom << c.srSelection.Right;
}
else cout << "\n\nError: " << GetLastError();
Whatever I'm selecting or I'm doing, always c.dwFlags will be 0 ...

While loop condition not working

Well basically the condition for healthtwo causes the program to stop but not healthone for some reason
complete code: http://en.textsave.org/CmN
if (chance<=rando) {
cout << " " << endl;
cout << "Hit! Dealing " << attackp << " Damage!" << endl;
healthtwo=healthtwo-attackp;
}
else {
cout << " " << endl;
cout << "Miss!" << endl;
}
chance=1+rand()%23;
if (chance<=rando) {
cout << "Comp Used " << comattackname << "!" << " Hit!" << " Dealing " << attackcp << " Damage" << endl;
cout << " " << endl;
healthone=healthone-attackcp;
}
else {
cout << "Comp Used " << comattackname << "!" << " Miss!" << endl;
cout << " " << endl;
}
} while (healthone>=0 || healthtwo>=0);
That should be a logical and (&&). After all, you want to check whether the health of both contestants is greater or equal to zero.

'stdx’ is not a namespace-name error being shown for a ptr_vector program

I've been trying a program from codeproject, about ptr_vector, and while compiling, the above error is shown.
Googling shows no hope to solve this problem. Could anyone here help out?
Here's the entire code (am compiling with gcc 4.2.2)
#include <iostream>
#include <string>
#include <boost/ptr_container/ptr_vector.hpp>
using namespace std; // for cout, endl, find, replace, ...
using namespace stdx; // for ptr_vector, ptr_vector_owner
using namespace boost;
int main()
{
cout << "---- ptr_vector demo ----" << endl;
ptr_vector<string> ptv;
ptr_vector_owner<string> owner (ptv); // scope-guard: owner of new-ed objects
ptv.push_back (new string ("Peter"));
ptv.push_back (new string ("Paul"));
ptv.insert (ptv.end(), new string ("Margaret"));
cout << " 1: " << ptv.front() << " " << ptv.back() << endl;
cout << " 2: " << ptv[1] << " " << ptv.at(2) << endl;
cout << " 3: " << *ptv.begin() << " " << *(ptv.begin() + 1) << endl;
cout << " 4:";
for (ptr_vector<string>::iterator it = ptv.begin(); it != ptv.end(); ++it)
cout << " " << *it;
cout << endl;
ptv.sort();
cout << " 5: " << ptv[0] << " " << ptv[1] << " " << ptv[2] << endl;
ptv.sort (greater<string>());
cout << " 6: " << ptv[0] << " " << ptv[1] << " " << ptv[2] << endl;
ptr_vector<string>::iterator iter;
iter = find (ptv.begin(), ptv.end(), "Paul");
if (iter != ptv.end())
cout << " 7: " << *iter << endl;
replace (ptv.begin(), ptv.end(), string ("Paul"), string ("Fred"));
cout << " 8: " << ptv.begin()[1] << endl;
string* str = ptv.pop_back();
cout << " 9: " << *str << " - size: " << ptv.size() << endl;
delete str;
delete ptv.detach (ptv.begin());
cout << "10: " << ptv[0] << " - size: " << ptv.size() << endl;
ptr_vector<string> ptvTwo;
ptr_vector_owner<string> ownerTwo (ptvTwo);
ptvTwo.push_back (new string ("Elisabeth"));
ptvTwo.push_back (new string ("Susan"));
ptv.swap(ptvTwo);
if (ptv < ptvTwo)
cout << "11: " << *ptv.begin() << " - size: " << ptv.size() << endl;
return 0;
}//main
stdx is not a standard namespace, it is defined by the particular implementation you are trying to use. You are not using the header file include #include "ptr_vector.h" inside which namespace stdx exists. Currently the ptr_vector you are using is being included from boost namespce. That begs the question, if you can use boost why do you want use stdx namespace solution.