Any suggestions to why this loop isn't executing? - c++

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>> !

Related

Getting empty a char that needs to be empty at the beginning of every iteration of a loop function

I created a char called aux that I need just as a variable in which to process the sufixes of the achar and to check if these sufixes are prefixes of the b char. So, I'm trying to get this aux char overwriten at every iteration (or if I can say, to get it "empty" and ready for the next iteration when the program will write in it the characters from the iterationi+1)so that i don't need a aux of a large size and i really don't want to risk to have inaux characters from the previous iteration. So, how do I get it empty, or how do I overwrite the char, especially if in thei+k iteration the program would send less characters than in the previous iteration, so it can't not really overwrite because there are less charaters and we could end up with characters from 2 iterations in aux. Here are the lines where i tried to do this. min is the minimum between strlen(a) and strlen(b) and na is strlen(a).The algorithm is working properly but just if I declare a large physical dimension for aux ... like aux[100].
#include <iostream>
#include<string.h>
using namespace std;
int main()
{ char a[31], b[31], aux[31];
unsigned int i, na, nb, min;
na = strlen(a);
nb = strlen(b);
if (na < nb)
min = na;
else
min = nb;
cout << "Define a:";
cin >> a;
cout << "Define b:";
cin >> b;
cout << endl;
for (i = 0; i < min;i++)
{ aux[0] = '\0';
strcpy_s(aux, a + (na - i - 1));
if (strstr(b, aux) == b)
cout << aux << " ";
}
cin.get();
cin.get();
}
set your aux's first element to \0 or use memset(aux, 0, sizeof(aux))
EDIT:
aux[0] = '\0';
puts the end sign to the start of the string, making it empty. So, if you copy to this (empty) string again, the copied data will override the previously written data, making your memory handling more efficient, which is the exact goal of this question.
Based on your code, the variable aux must be big enough to contain the whole of the variable pointed at by a so if you've declared that to be, for instance, char a[50]; then you also need char aux[50];, it cannot be smaller...
On the other hand, to reset aux at each iteration simply write aux[0] = '\0'; as the first line inside the loop...
You are initializing na and nb before a and b are filled with input, so you'll get a random size from strlen. Give it a try, you'll see. As such, your algorithms break.
Try moving it below the input.
cout << "Define a:";
cin >> a;
cout << "Define b:";
cin >> b;
cout << endl;
na = strlen(a);
nb = strlen(b);
if (na < nb)
min = na;
else
min = nb;
I've tried it with this order and it works as expected, without the need to aux[0] = '\0';

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

What does an array equal to without the [ ]? 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++).

Printing elements of an array in C++, and inner versus outer initialization of variable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm having a super simple problem, but I also had a question, so I figured I'd post both.
First of all, I'm not sure what's not working about this program cycling through an array and out putting the values. What's happening now, is that it just outputs the last value in the array.
int myArray[10] = {0,1,1,2,3,5,8,13,21,34};
int i = 0;
for( i = 0; i < 9; i++);
{
cout << i + 1 << '\t' << myArray[i] << endl;
}
that's not working for some reason, but I also wanted to know why, if I initialize the i variable inside the for loop, it says myArray[i] inside of the for loops, at the cout, isn't initialized at all. Peculiar to me.
I just tested the following code and it worked:
#include <iostream>
using namespace std;
int main() {
int myArray[10] = {0,1,1,2,3,5,8,13,21,34};
for(int i = 0; i < 10; i++) {
cout << i + 1 << '\t' << myArray[i] << endl;
}
}
Notice the syntactical changes that were made. Also you were previously leaving out the last element in the array.
What's important to note is that a semicolon is a null statement. By placing a semicolon after a for loop, you are executing the null statement (i.e. do nothing) for the total number of iterations through the loop. Afterwards, the code inside the curly braces is run as if it were regular code in the body of your method. That's why only the last iteration was printing, because the for loop had "done nothing" for all the other iterations but still incremented i. Therefore, when the code within the braces ran, it did so for the last expected iteration.
for( i = 0; i < 9; i++);
// ^here
Remove the extra semicolon. The original code in your question is equivalent to:
for( i = 0; i < 9; i++)
{
//do nothing
}
{
cout << i + 1 << '\t' << myArray[i] << endl;
}
Now you can declare i inside the for loop:
for( int i = 0; i < 9; i++)
{
cout << i + 1 << '\t' << myArray[i] << endl;
}
You have an extra semicolon here:
for( i = 0; i < 9; i++); // there should be no semi-colon at the end of this line.
// ^ remove this!
What's happening is that the compiler iterates the loop completely, running the "empty" loop body (that extra semicolon). After the loop is done, it reaches your cout statement.
for( i = 0; i < 9; i++);
// ^ THIS TINY PIECE OF ABOMINATION
{
cout << i + 1 << '\t' << myArray[i] << endl;
}
Remove it.
The block below the for statement isn't associated with it because the for is actually associated with a null statement (indicated by the ; immediately after the for()).
You should also put your declaration of i inside for
for(int i = 0; i < 9; i++) {
...
That way, you limit its scope and makes you less prone to some errors.

for loop not running, trying to iterate backwards through array elements

To practice using pointers and arrays i'm trying to do a simple program capable of converting a binary input to denary.. i think i have a good idea for the logic but i haven't even got round to trying to implement it because im struggling to get my for loop running!
It seems silly but i know the code inside the for loop works fine outside of it, so it must be something wrong with the condition..? im trying to start at the back of the char array (navigating using pointers) and output each char(as an int) up to the first element.
So the desired output is "0 - 1 - 0 - 1 -"
#include <iostream>
using std::cout;
using std::endl;
//prototypes
void binaryToDenary(const char* input, int& inputLength);
int main(){
const char binaryInput[] = {1,0,1,0};
int inputLength = sizeof(binaryInput)/sizeof(binaryInput[0]);
binaryToDenary(binaryInput, inputLength);
return 0;
}
void binaryToDenary(const char* input, int& inputLength){
//testing some stuff--- this all works as expected
//cout << input[2] << " " << (int)*(input+2) << " " << inputLength <<endl;
int i;
for(i = inputLength; i < 0; i--){
cout << (int)*(input+i) << " - ";
}
}
Your for loop should be this:
for(i = inputLength -1 ; i >= 0; i--)
{
cout << (int)*(input+i) << " - ";
}
There are two problems in your code:
i = inputLength which should be i = inputLength -1
i < 0 which should be i >= 0
Also, change the second parameter type from int & to int:
void binaryToDenary(const char* input, int inputLength) //now its better!
The type int& reduces the use cases, and benefits almost nothing. If you use int &, then all of these would give compilation error:
const int inputLength = sizeof(binaryInput)/sizeof(binaryInput[0]);
^^^^ note this
binaryToDenary(binaryInput, inputLength); //compilation error
binaryToDenary(binaryInput, sizeof(binaryInput)/sizeof(binaryInput[0])); //error
binaryToDenary(binaryInput, 4); ////compilation error
So use int, and all of the above would compile fine!
Array indexes start from zero, so the last element is at inputLength - 1. With i < 0 you exit from the loop immediately as that never be true...
for(i = inputLength - 1; i >= 0; i--){
cout << (int)*(input+i) << " - ";
}
for(i = inputLength; i < 0; i--)
will run only if inputLength is less than 0, which is not possible?
You need:
for(i = (inputLength-1); i >= 0; i--)
^^^^^^^^^^^^^^ ^^
C arrays are 0 based so a valid index is given by
(0 <= i) && (i < array_length)
In your program, this means that the position of the last digit in your initialization should be inputLength - 1 and the loop condition should be i >= 0.
(As for why you loop is not running, at the start you have i == inputLength, so i is positive, failing the i < 0 condition immediately).
You want to run as long as i is bigger (or maybe equal) to zero. You were trying to run the loop as long as i was less than zero, and beginning with a value greater than zero results to that you never enter the loop.
for(i = inputLength; i > 0; i--){
cout << (int)*(input+i) << " - ";
}
You must check for iteration loop variable i to be positive..
However you should use a STL iterator on the binary input vector and not loop on it's content in a c fashion, if you want to practice C++, possible solution could be:
vector<char> binaryInput;
binaryInput.push_back(1);
binaryInput.push_back(0);
binaryInput.push_back(1);
binaryInput.push_back(0);
vector<char>::iterator it;
for ( it=myvector.begin() ; it < myvector.end(); it++ ){
cout << " " << *it << endl; //or whatever you need to do with vector content
}