Array values coming out incorrectly in C++ - c++

I have been working at this for over 2 hours. I have isolated my problem to one piece of code.
The problem is with my array. It is outputting really big negative values. The values I am feeding into the array are correct. I am experienced with java, but this is my first C++ program.
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
string inputString;
cin >> inputString;
cout << inputString << endl;
int mainArray[10];
for(int x = 0; x < inputString.length(); x++){
int valFound = inputString[x]-48; //minus 48 to change from ascii to int
mainArray[valFound]++;
cout << mainArray[valFound];
}
return 0;
}
Any help would be much appreciated, this is making me crazy.

Your array is being default initialized. Default initialization of the type int leaves it "with garbage". You need to initialize it to 0 explicitly:
int mainArray[10] = {0};

This is because arrays need to be initialized. Add this to your code:
for (int i = 0 ; i != 10 ; i++) {
mainArray[i] = 0;
}
Alternatively, you can use memset:
memset(mainArray, 0, sizeof(mainArray));

Related

Why is my array not printing out in reverse after being populated with 20 randomly generated strings

#include <iostream>
#include <vector>
#include <ctime>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
string Alphabets[26] = { "Hey","How","Are","you","Doing","Today","My","Name",
"Is","John","Its","Great","to","finally","meet","you","today",
"wow","summer","was","long","school","has","started","now"};
string RandString[20];
srand(time(NULL));
for (int k = 0; k < 20; k++) {
int temp = rand() % 26;
RandString[k] = Alphabets[temp];
}
for (string RandomString : RandString ) {
cout << RandomString << endl;
}
for (int i = 20; i >= 0; i--) {
cout << RandString[i] << endl;
}
}
I'm having trouble understanding my code to an extent. Right now, my code is randomly generating 20 strings into an array. I have one range for loop that shows the strings that we're picked by the random string generator. But my issue comes with the last part of the code and that is to reverse it. I believe what I'm doing wrong is that I'm trying to reverse strings that haven't been randomly generated yet. Therefore, I believe that's why nothing appears, and if this is the case, I have forgotten how to take an array that's been fully populated and then assign it to a different variable which 'I think also has to be an array'. I know this is a silly question but could someone tell me why, if this array isn't being populated when called outside of the for loop why is the ranged for loop able to then print it out?

How do I specify the amount of random numbers in my code in C++

I tried reading other questions to find the answer to my question but I got tired of seeing the answer being in a different coding language. I want to change the amount of numbers in my random error code. I am genuinely new to this so please no rude comments.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main () {
int i,j[3];
srand( (unsigned)time( NULL ) );
I set the array for j to 3 so I could try and get a maximum of 3 numbers.
for( i = 0; i < 1; i++ ) {
j[3] = rand();
cout <<"Error code: " << j << endl;
}
return 0;
}
Here is where the error comes in, the output of the code only sends the variable address instead of the random number. I really need help with this before I could continue my project. Please help.
Edit: Variable address is "0x7ffc9b46ed5c"
I can assume you want to set an array of size 3 to random numbers.
I set the array for j to 3
j[3] = rand();
You're not doing that, you're setting the 4th element in your array j as a random number, which happens to be out of bounds and invokes undefined behavior.
cout <<"Error code: " << j << endl;
Outputs the address of the first element in array j. Not the whole array.
How i would do it:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int j[3];
for (int i = 0; i < 3; ++i)
j[i] = rand(); //sets every index of the array to rand()
cout << "Error code: ";
for (int i = 0; i < 3; ++i)
cout << j[i] << '\n'; //outputs all values from the array
return 0;
}
When you declare an array of size 3 by int j[3] you can refer to the first value by j[0], second value by j[1], and the third value by j[2]. If you want to display every value from your array you can use a normal for loop (using j[i]) or a range based for loop:
for(int& i : j)
cout<<i; //this loop will display every component from your array

Dynamically allocated 2D Array issue

I am trying to understand what I am doing wrong when attempting to dynamically allocate the 2D array "allWordMultiArray" and assign values to it.
I've been reading a lot of articles online (and in Stackoverflow in particular) and tried to implement it in a lot of ways but unsuccessfully. using C++ 14.
So, the following code creates a warning of "Using uninitialized memory '*allWordMultiArray[i]'".
Obviously, when trying to cout the values in the 2D array it prints garbage.
Can someone point to me what the problem is?
Here's a summary of the code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int letters = 26;
int main() {
....
int numWords, pos;
string input;
int** allWordMultiArray;
cin >> numWords;
allWordMultiArray = new int* [numWords];
for (int i = 0; i < numWords; i++) {
cin >> input;
allWordMultiArray[i] = new int[letters];
for (unsigned long int j = 0; j < input.size(); j++)
{
pos = (input[j] - 'a');
//Here is the problem. Garbage values
allWordMultiArray[i][pos]++;
}
}
return 0;
}
Your help is very much appreciated.
This line:
allWordMultiArray[i] = new int[letters];
does allocate memory for an array, but the values in the array are indeterminate. Reading from these values, like here:
allWordMultiArray[i][pos]++;
will invoke undefined behavior.
Just initialize the array when you allocate it:
allWordMultiArray[i] = new int[letters] {};
// ^^

How to use vector<vector<string>> in c++?

I saw in c++ code the following:
vector<vector<string>> arr(n);
I was unable to understand how to use it...
Can anyone explain what is it and how to use var arr?
This is definition of 2 dimension-array of strings with size n.
You can use all places in the upper vector as another string vector.
Look at the following example:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string a = "AAAA";
string b = "BBBB";
string c = "CCCC";
int n = 3;
vector<vector<string>> arr(n);
arr[0].push_back(a); // I add string 'a' to end of first vector in 'arr'
arr[0].push_back(b);
arr[1].push_back(c);
for (int i = 0; i < arr[0].size() ; i++) { // print all string in first vector of 'arr'
cout << arr[0][i] << " ";
}
}

Why does it crash when I reach my 2D Array? out_of_range

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <stdlib.h>
using namespace std;
int gradeExam(string answerKeyARR[]);
int main()
{
const int QUESTIONS = 10;
const int MAX_STUDENTS = 250;
ifstream inFile;
ofstream outFile;
inFile.open("grade_data.txt");
outFile.open("grade_report.txt");
string ansKey;
inFile >> ansKey;
string answerKeyARR[QUESTIONS];
//Loop for storing each answer into an array rather than all in a single string.
for (int j = 0; j < QUESTIONS; j++)
{
answerKeyARR[j] = ansKey.substr(j,1);
}
int i = 0;
int numStudents = 0;
string studentAnswers[MAX_STUDENTS];
//Loop to read in all answers into array and count number of students.
while (!inFile.eof())
{
inFile >> studentAnswers[i];
numStudents++;
i++;
}
//WHY DOES IT CRASH HERE?!
string studentAnswersARR[numStudents][QUESTIONS];
for (int k = 0; k < numStudents; k++)
{
for (int l = 0; l < QUESTIONS; l++)
{
studentAnswersARR[k][l] = studentAnswers[l].substr(l,1);
cout << studentAnswersARR[k][l];
}
}
inFile.close();
outFile.close();
return 0;
}
Okay, so basically once it gets to the part where it's removing the substring, it crashes. It works perfectly fine for retrieveing the answerkey answers, so why the hell is it crashing when it gets to this point? This is still a WIP for basic coding 2.
Also, when I change variable 'l' to, say, position 0, it works. What gives?
There are multiple issues with your code that may cause problems.
First, your input loop is not bounded properly. It should stop at MAX_STUDENTS, but you fail to check for this limit.
Second, do not use eof() to check for the end of file. There are many posts on SO discussing this.
while (!inFile && i < MAX_STUDENTS)
{
inFile >> studentAnswers[i];
numStudents++;
i++;
}
The next issue is the line you highlighted in your question. It probably crashes due to stack space being exhausted. But the code you have uses a non-standard C++ extension, and once you do that, then the rule as to what that line really does internally is up to the compiler vendor.
So to alleviate this with using standard C++, the following can be done:
#include <vector>
#include <string>
#include <array>
//...
std::vector<std::array<std::string, QUESTIONS> >
studentAnswersARR(numStudents);