What does an array equal to without the [ ]? c++ - c++

for some reason the first number to print out doesn't abide by the for loop in the main function, telling it to range from 0-10; but when
void printArray(int augArray[5])
{
cout << *augArray; //this line is taken out, the for loop proceeds with normal
for (int i = 0; i < 5;) //outputs, when the first line is kept also the for loop only
{ //produces 4 other numbers, just curious to why this is
cout << augArray[i] << endl; //happening, thanks.
i++;
}
}
int main()
{
srand(time(0));
int anArray[5];
for(int j = 0; j < 5;)
{
anArray[j] = rand() % 11;
j++;
}
printArray(anArray);
cout << anArray;
}

When an array name is used in an expression without square brackets following it, its value is equal to the pointer to the initial element of the array, i.e. augArray in an expression is the same as &augArray[0]. Therefore, *augArray is the same as *(&augArray[0]), which is simply augArray[0] (the asterisk and the ampersand cancel each other).
The reason the output looks strange is that you did not put an end-of-line character after you printed *augArray. The "weird number" that you see in the output is actually the initial element of the array repeated twice.

It should works just fine except the first output is mixed with the following outputs. To see it more clearly, you should put a newline after you print out the first element:
Change
cout << *augArray; // print the first element
to
cout << *augArray << endl; // print the first element and go to a new-line
See it live: http://ideone.com/y16NeP.
Sidenote: you can simply put i++/j++ to the for-line, like for (int i = 0; i < 5; i++).

Related

Checking For Element Position in Array and Printing New Line After Checking

So I've written this code and it works until I try implemented a part of my second for loop where I try to print a new line. It is suppose to print a new line after the 8th element being printed. Any help appreciated.
// Construct a for loop that runs backwards through the array,
// starting at the last element and ending at the first.
for (int i = arraySize; i > 0; i--) {
// Inside this for loop, print the ith element of the array
// and a tab, with NO newline characters.
cout << newArray[i-1] << " ";
// If this element is the 8th one on its line, print a
// newline character to advance to the next line.
// Also inside this for loop, add the value of the ith
// element to the current value of the double for the sum
// of elements.
//ISSUE IS HERE
if (newArray[i-8] = newArray[7]) {
cout << "\n";
}
sumOfElements += newArray[i-1];
}
I've only pasted the for loop that has the issue, I don't believe any other information is necessary as I know it works up until this point.
You want comparison (==) not assignment (=). But in any case this
if (newArray[i-8] = newArray[7]) {
cout << "\n";
}
is wrong. For i < 8 you will access negative indices, which is out-of-bounds. To check if you are printing the 8th element from the array you only need to look at the index:
if (i == 7) {
cout << "\n";
}
It you rather want to put a new line after 8 elements have been printed then it is
if (i == arraySize-7) {
cout << "\n";
}
If instead you want to put a new line after each 8 elements that have been printed then it is
if ( (i - arraySize - 1)%8 == 0) {
std::cout << "\n";
}

How to check if a character matches another character in a char array?

I'm currently trying to figure out how I can replace a certain character in a char array using a for loop to check each index position in the array. However, when I assign the correct character to the char variable "letterGuessed" and it is checked it instantly goes to the else statement. This leaves the character as an asterisks. This is the code below:
#include <iostream>
#include <cstring>
void hide_Word(char hide[], int size);
int main()
{
char hiddenWord[] = "Hello";
char displayWord[30] = { 0 };
int length = strlen(hiddenWord);
hide_Word(displayWord, length);
std::cout << hiddenWord << std::endl;
std::cout << displayWord << std::endl;
char letterGuessed;
std::cout << "Enter a character: ";
std::cin >> letterGuessed;
for (int i = 0; i < length; i++)
{
if (displayWord[i] == letterGuessed)
{
letterGuessed == displayWord[i];
}
else
{
std::cout << "*";
}
}
std::cout << std::endl;
std::cout << displayWord << std::endl;
std::cin.get();
return 0;
}
void hide_Word(char hide[], int size)
{
for (int i = 0; i < size; i++)
{
hide[i] = '*';
}
}
When I compile your code I get the warning
main.cpp|27|warning: statement has no effect [-Wunused-value]
for the line
letterGuessed == displayWord[i];
This, for one, means that what you do to make correctly guessed letters visible is achieving nothing. Reading and considering warning messages is really helpful, you know.
I guess that your goal here is to turn the "*", which you filled displayWord with, should be replaced by the correctly guessed character.
That would better be achieved by an assignment using =.
letterGuessed = displayWord[i]; /* still unhelpful */
But that line would still not achieve anything visible.
To change something in the displayWord, it should be what gets the guessed character as a new value, not the other way around.
displayWord[i] = letterGuessed;
This is however still not satisfying, because you don't do this in the right situation.
Let's have a look at the condition which determines when you do it.
if (displayWord[i] == letterGuessed) /* unhelpful */
This will trigger, when the guessed character is an asterisk "*", because displayWord is filled with asterisks early on.
Which means that the condition only triggers if the user guesses an asterisk, which is unlikely. Even if it happens, the result is to overwrite an asterisk with an asterisk.
The condition you need should not check the asterisk-filled displayWord, it should instead check the "Hello"-filled hiddenWord.
if (hiddenWord[i] == letterGuessed)
In total, the code should hence be
for (int i = 0; i < length; i++)
{
if (hiddenWord[i] == letterGuessed)
{
displayWord[i]=letterGuessed;
std::cout << letterGuessed;
}
else
{
std::cout << "*";
}
}
This turns an asterisk in the displayed word into the correctly guessed character at each found position.
Note that I added an output of the guessed letter, to complete the letter-by-letter output. I guess you want to delete that output, or the word-output after the loop, so that the filled in word is only seen once.
Output:
Hello
*****
Enter a character: l
**ll*
**ll*

Using file input to input integers

I am stuck here having trouble figuring out as to why this loop is not inserting the integers from a text file into an array.
I have a textfile that contains 100 integers, all separated by spaces. I am trying to insert these integers into an array. However when I output, for example a[2], it outputs 0, leading me to believe that the numbers are not being inserted into the array.
listFile.open("unsortedlist.txt");
cout << endl << "Unsorted list = ";
for (int i = 0; i < 100; i++)
{
while (listFile >> individualNum )
{
a[i] = individualNum;
cout << individualNum << ", ";
}
}
cout << "\n" << a[1] << "\n";
Because of the while statement, all the numbers that are successfully read are assigned to a[0] only. As a consequence, the final value of a[0] is the last valid input while nothing is assigned to any of the other elements of a.
You can use something like:
for (int i = 0; i < 100 && listFile >> individualNum; i++)
{
a[i] = individualNum;
cout << individualNum << ", ";
}
The inner loop will diligently read every number from the file.
And assign every number to a[i]. The same array element, each and every time.
On the first iteration of the outer loop, i is 0, so the code will read every number from the file, assigning each number to a[0].
When the inner loop reaches the end of the file, it will terminate. Then, the outer for loop will increment i to 1, iterate again, and run the inner loop. Since the entire file has been read, the inner loop will not do anything. Neither it will do anything more, for the remaining 98 elements of the array.
The loop should probably be, simply:
for (int i = 0; i < 100; i++)
listFile >> a[i];
Keep in mind that this will work correctly, of course, only when there are exactly 100 integers in the file.

Any suggestions to why this loop isn't executing?

I have written the function below, which groups charterers together before encountering a space and saves each group in a vector, once a space is encountered it should look for another group and do the same thing over and over!
My debugging so far indicates that the for loop within the if statement is not executing for some reason.
char const* MathematicaLib::IsThisAnEquation(char const* equation){
// execute PEMDAS here
vector <char const*> SeperatedValues;
char *TempGH = "";
int temp = 0;
int SOG = 0; //start of group
//cout << equation[2] << endl; // used to test whether the funcion is reading the input parameter
for (int j = 0; j < strlen(equation); j++)
{
if (isspace(equation[j])) {
//cout << "processing" << endl; // used to confirm that its reading values until a space is encountered
for (int n = SOG; n < j - 1; n++){
TempGH[temp] = equation[n];
temp++;
SOG = j + 1; //skip charecter
cout << "test"; //this does not print out meaning that the loop dosen't execute
}
temp = 0;
SeperatedValues.push_back(TempGH);
}
}
for (unsigned int p = 0; p < SeperatedValues.size(); p++){ // used for debugging only
cout << SeperatedValues[p] << endl;
cout << "This should be reading the vector contents" << endl;
}
return "";
}// end of IsThisAnEquation
Assume that the value I am passing to the function is "123 1", also assume that the first character of the parameter is never a space. This means that when a space is detected then n == 0 AND j-1 == 2 (j-1 indicates the end of the group of characters while n = the start) the loop should cause the characters in position 0 to 2 (123) to be pushed into the vector, thus j is not == 0 or -1.
The loop is not directly embedded under the first for loop rather it is under the if statement, shouldn't this force to only execute if the condition within the if statment is true? rather than follow the rules of embedded loops execution?
Any suggestions to why this loop isn't executing?
I have reviewed the code over and over to spot any logical errors, but I couldn't find any so far!
My bad if (isspace(equation[j]) was the root of all evil, this condition was not being met because std::cin >> equation does not register spaces, replacing it with this std::getline(std::cin, equation); managed to solve the problem, the for loop now executes.
Thanks to #PaulMcKenzie and #Joachim Pileborg for pointing out the issue of modifying string literals.
Sorry I didn't mention that I was passing the parameter through std::cin>> !

Code crashes. Trying to remove characters from char array C

I am basically trying to store everything after a certain index in the array.
For example, I want to store a name which is declared as char name[10]. If the user inputs in say 15 characters, it will ignore the first five characters and store the rest in the char array, however, my program crashes.
This is my code
char name[10];
cout<< "Starting position:" << endl;
cin >> startPos;
for(int i= startPos; i< startPos+10; i++)
{
cout << i << endl; // THIS WORKS
cout << i-startPos << endl; // THIS WORKS
name[i-startPos] = name[i]; // THIS CRASHES
}
For example, if my name was McStevesonse, I want the program to just store everything from the 3rd position, so the end result is Stevesonse
I would really appreciate it if someone could help me fix this crash.
Thanks
Suppose i is equal to 3. In the last iteration of the loop, i is now equal to 12, so substituting 12 in for i, your last line reads
name[12-startPos] = name[12];
name[12] is out of bounds of the array. Based on what you have shown so far, there is nothing but garbage stored in name anyway before you start doing this assignment, so all you're doing is reorganizing garbage in the array.
Please in future: post full compilable example.
A simple answer is that your array maybe is out of bound, since you don't provide full example its hard to know exactly.
Here is a working example:
#include <iostream>
using namespace std;
int main() {
int new_length, startPos;
int length = 15;
char name[15]= "McStevesonse";
cout<< "Starting position:" << endl;
cin >> startPos;
if(new_length <1){ // you need to check for negative or zero value!!!
cout << "max starting point is " <<length-1 << endl;
return -1;
}
new_length=length-startPos;
char newname[new_length];
for(int i= 0; i<new_length; i++){
newname[i] = name[i+startPos]; // THIS CRASHES
}
cout << "old name: " << name << " new name: " << newname << endl;
return 0 ;
}
To put it simply, change this:
for(int i= startPos; i< startPos+10; i++)
To this:
for(int i= startPos; i<10; i++)
You should be fine with that.
Explanation:
At some point, when you use the your old loop, this name[i-startPos] = name[i] would eventually reach an array index out of bounds and causes the crash.
Don't forget to clean up/hide the garbage:
Doing so, would cause the output to produce some kind of garbage outputs. If you got a character array of 'ABCDEFGHIJ', and have chosen 3 as the starting position, the array would be arranged to 'DEFGHIJHIJ'. In your output, you should atleast hide the excess characters, or remove by placing \0's