Convert userInput (string) to UserInput(int) mid for loop - c++

I am working on a program that has to do with arrays. I decided that the input the user provides to be a string to later being converted to an integer once it is determined it is one. This way the program wouldn't run into an error when words/letters are entered. The issue I am having is the conversion from string to int. I want to change that because later in the program I am going to search the array for a given value and display it and its placement in the array. This is the code I have thus far:
#include <stdio.h>
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main()
{
const int size = 9 ;
int x, UserInput[size], findMe;
string userInput[size];
cout << "Enter "<< size <<" numbers: ";
for (int x =0; x < size; x++)
{
cin >> userInput[x];
if (check_number(userInput[x]))
{//the string is an int
}
else
{//the string is not an int
cout<<userInput[x]<< " is a string." << "Please enter a number: ";
cin >> userInput[x];}
}
int i;
for (int i =0; i < size; i++)
{
int UserInput[x] = std::stoi(userInput[x]); // error occurs here
}
for (int x= 0; x< size; x++)
{
if (UserInput = findMe)
{
cout <<"The number "<< UserInput[x] << "was found at " << x << "\n";
}
else
{
//want code to continue if the number the user is looking for isn't what is found
}
}
return 0;
}
Made comments here and there to kinda layout what I want the code to do and whatnot. I apperciate any help you can give, thank you.

This code:
int UserInput[x] = std::stoi(userInput[x]);
declares an int array of size x, to which you are assigning a single int (the result of std::stoi), which obviously doesn't work.
You need to assign an int to a particular index of the existing array, like this:
UserInput[x] = std::stoi(userInput[x]);
Given this comparison if (UserInput = findMe), which should actually be if (UserInput == findMe), it seems you want to declare a single int which stores the result of std::stoi. In that case, you should use a different name than the array, and write something like this:
int SingleUserInput = std::stoi(userInput[x]);
Also, please indent your code consistently, and compile with all your warnings turned on. Your code will be easier to read, and the compiler will point out additional problems with your code. And please don't use using namespace std;, it's a bad habit.

I don't understand why do u even need to use another loop to convert the string value to int. stdio.h header file does provides with preinstalled functions to make your work easier...
for (int x =0; x < size; x++)
{
getline(cin,userInput1[x]);
UserInput[x]=stoi(userInput1[x]);
}
stoi() function converts the string input to int, and you can call it dynamically as soon as you enter your string input,It will make you work easier and reduce the time complexity

Related

Some test cases aren't passing

#include <iostream>
#include <vector>
int i=0; //points at the current stack that we are working with
int box=0; //no. of boxes held by the crane
int64_t H; //max. height of the stacks given in the que.
int main()
{
int n, value; //storing no. of stacks and creating an additional variable value to store operations
std::cin>> n >> H;
int64_t arr[n]; //storing the no. of boxes each stack has in an array
std::vector<int> arr2; //storing the operations we have to perform in a vector
for(int j=0; j<n; j++){std::cin>> arr[j];} //getting arr
while(std::cin>>value) //getting arr2
{
arr2.push_back(value);
}
for(int xy=0; xy<n; xy++){if(arr[xy]>H){return 0;}} //ensuring that all stacks have no.of boxes less than max. height
if(arr2.size()<1 || arr2.size()>10e5 || n<1 || n>10e5 || H<1 || H>10e8){return 0;} //constraints given in the que.
int k=0; //creating a variable to keep count of how many programs we have already executed
while(k<arr2.size()){
if(arr2[k] == 1){MoveLeft();}
else if(arr2[k]==2){MoveRight(n);}
else if(arr2[k]==3){PickBox(arr, i);}
else if(arr2[k]==4){Dropbox(arr, i);}
else if(arr2[k]==0){k=arr2.size();}
k++;
}
for(int j=0; j<n; j++){std::cout<< arr[j] << " ";} //printing the arr after executing the code
return 0;
}
This is a question from a past year ZCO. And the above code is what I wrote to solve the prob.
The four functions Moveleft, MoveRight, Pickbox, Dropbox have been defined in the same file but aren't shown here because I think there's no issue with them.
When I submit the code, all test cases passed except 2. I don't know what is the problem with my code. Pls help me.
I have tried my best to make the code readable. Sorry if the code looks messy.
With the method you're trying to define an array with a user-input length is unfortunately invalid in C++.
But fortunately, there are basically two methods use to allocate arrays dynamically.
Method 1: Using Vectors
Vector is an important part of C++. It has a lot of features (e.g. its size don't need to be defined static unlike a normal array does, can redefine array size, etc.) An example's given:
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> vArray; // vector<> declaration
int size = 0;
int getInput = 0;
std::cout << "Enter an array size: ";
std::cin >> size;
for (int i = 0; i < size; i++) {
std::cout << "Enter a value: ";
std::cin >> getInput;
vArray.push_back(getInput); // inserts one+ container and data in it
}
for (int i = 0; i < vArray.size(); i++) {
// retrieving contained data...
std::cout << vArray[i] << std::endl;
}
return 0;
}
Method 2: Using 'new' Keyword with Pointed Variable
The simple use of new will help you to achieve your requirement. It's less recommended since already there's concept of vectors which actually works efficiently than arrays. Let's take a look into a simple program:
#include <iostream>
int main(void) {
int *pArray;
int size;
std::cout << "Enter an array size: ";
std::cin >> size;
pArray = new int[size]; // initializing array with dynamic size
for (int i = 0; i < size; i++) {
std::cout << "Enter value: ";
std::cin >> pArray[i];
}
for (int i = 0; i < size; i++) {
std::cout << pArray[i] << std::endl;
}
delete[] pArray;
return 0;
}
Both are nice options to work with, but it's recommended by most using vector<>.

Problem with storing 10 integers into an array C++

Ok, I'm very confused as to why this happens. All I'm trying to do is put 10 integers from input into an array. Why is this happening.
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
If you could please tell me where I'm going wrong, that would be very much appreciated. Thank you!
From how your code is written, you're only adding the user's input to the [10] element of intArray[] within that for loop you created. Additionally, any information added to the array at intArray[10] or beyond is placed out of bounds.
The only way I can really demonstrate what I mean is...
for (int i = 0; i < 10; i++)
{
std::cout<<"Enter a number:";
std::cin >> intArray[i];
}
Another thing I noticed is you're creating another array with the same name in your printData method. You should instead pass the intArray you're filling up with information to this method and use it to display your information.
The problem lies in this block of code-
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
As mentioned in other answers and comments you are storing all the values in the 10th memory slot of the array.
As per your comment
I forgot to mention, the output is just random integers and characters. EX: 00B3F724
00B3F724=> These are the memory address allocated to the array and which will hold the elements which will be inserted.
How array actually works-
float myArray[10];
The above snip creates 10 units of memory space. The units differ on the type which the array will hold. In this case it is holding float values, so each memory space will be of 4 bytes. All of these spaces have an address for lookup and other operations. All these spaces are expecting a float value to be inserted.
As you are using the loop you have to loop through the array(all the memory slots allocated to the array) and allocate a float element to each one of them and not only the last element(10th).
Effectively your for loop will become
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
Instead of intArray[10] insert values like this intArray[i]. As i will traverse through all the slots on every iteration of the loop insert a values to a slot.
Your code will look like
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
As you know if an array is declared as myArray[10], its index ranges from 0-9. Putting a value in myArray[10] will go out of bound and will produce garbage value.
In getData(float intArray[]) you are always overwriting the content of intArray[10] while it is out of bound so it is not being stored in an actual array. You should write your getData(float intArray[]) as following :
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cin >> intArray[i];
}
return 1;
}
Also in printData(float intArray[10]) you are only printing the base address of the array (i.e the name of the array gives the address of the 0th index).So the correct code would be:
void printData(float intArray[])
{
for(int i=0;i<10;i++)
{
cout << intArray[i]<<" ";
}
}
Simply change,
std::cin >> intArray[10];
to,
std::cin >> intArray[i];
What you are doing wrong:
you are storing the value at the 10th position (actually it is 11th position) again and again and the value at 10th position replaces with the new value again and also the 10th position doesn't exist in the array because the index of the array starts from 0, so your array has the index values from 0 to 9.

How to debug why the compiler crashes on my C++ program?

Code 1: supposed to take a matrix (m by n) size and then find the min value in each row. Doesn't show any errors, runs but the black screen (devc++) for the compiler simply crashes without doing anything and has a ridiculously high return value (3221225725 to be exact).
I'm not sure how to fix or improve it, also it works when the size of the matrix is constant, like instead of cin to get size a simple number makes it work. I am not sure why; I'm new to programming.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int m,n;
int B[m][n];
int A[m+1][n+1] = {0};
cin>>m;
cin>>n;
for (int x = 0; x < m; ++x)
{
for (int y = 0; y < n; ++y)
{
cout<< "Enter in value for row " << x << ", column " << y << ".\n";
cin>> A[x][y];
}
}
cout << "Input:" <<endl;
for (int x = 0; x < m; ++x)
{
for (int y = 0; y < n; ++y)
{
cout<< A[x][y] << "\t";
}
cout << "\n";
}
for (int x = 0; x < m; ++x)
{
for (int y = 0; y < n; ++y)
{
A[x][4] = A[x][1];
if (A[x][4] > A[x][y])
A[x][4] = A[x][y];
}
}
cout <<"Output:"<<endl;
for (int x = 0; x < m+1; ++x)
{
for (int y = 0; y < n+1; ++y)
{
cout << A[x][y] << "\t";
}
cout<<"\n";
}
getchar ();
return 0;
}
And this is code 2:
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
int i,j,R,C,Too;
double a[i][j];
float f;
Too=0;
cin>>R;
cin>>C;
for (int i=0; i<R; i++)
for (int j=0; j<C; j++)
{
f=i+j/2;
a[i][j]=sin(f);
if (a[i][j]>0)
{
Too=Too+1;
}
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
cout<<Too<<" Shirheg eyreg element bn"<<endl;
}
the elements in this matrix is generated by the formula f=i+j/2; a[i][j]=sin(f);
and simply outputs how many positive elements are there. for some odd reason the elements are always double like the output is something like:
0
0
0.841471
0.841471
and one other number then gets getting double and then a number and then double.
how to fix?
Strange return values and crashes when working in C++ are often a sign of uninitialized values. For example, consider the following:
int main() {
int m,n; // <-- declare 'm' and 'n', but we don't initialize them to have a value
int B[m][n]; // <-- use the values in 'm' and 'n' to allocate memory for 'B'
...
cin >> m; // <-- only now are you setting m to a value, but you already used it.
cin >> n; // <-- same thing with n.
...
}
The above code is wrong because it uses the variables identified by 'm' and 'n' before it sets them to have a particular value, so until you set their value (with cin) they just have whatever value happened to be sitting in memory at the time they were created.
Assigning a value to them is called "initialization" or initializing them the first time you do it. Before that they just hold that value from memory.
Ultimately, each line of code is using some variables and may be making assignments to other variables. So make sure each variable that is being used has already been initialized before you reach that line of code.
You will have to debug your own code in order to learn effectively, and the above example is not the only error or issue here, but a few basic tips to help you along the way:
Always look out for anything using uninitialized values like m and n
If it makes sense, initialize values as soon as they are created
i and j and k as variable names are usually declared only in a loop, because you usually only need them to exist inside the loop.
If you declare int i in a function, you should not declare int i in a loop within that function. The two i's now mean different things, which is confusing.
put spaces around your << and >> operators. It will make the code easier to read.
If you're having trouble, try printing out the value of a variable with cout and see if it makes sense. If not, there is a problem before that point in the program.
If you're having trouble, try working on one section of the code at a time until it behaves the way you expect.

C++ Debug Assertion Failed string arrays

I am coding an assignment for my class where a user will input 10 letter answers, and the program will return a grade. I recently changed my char arrays to string arrays, because I think it makes it easier to read.
I went to debug my code and am now getting the error "Deubug Assertion Failed." I do not know what this means or how to fix it.
Any help would be appreciated.
Thanks!
Below is my code:
// Lab 8
// programmed by Elijah Barron
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Function headers
string inputAnswers(string given);
int numCorrect(string correctAnswers, string given);
int main()
{
string correctAnswers = "BCADBADCAB";
string given;
int numRight = 0;
inputAnswers(given);
numCorrect(correctAnswers, given);
double grade = 10 * numRight;
cout << "Your quiz grade is " << grade << "%" << endl;
return 0;
}
//Get the answers
string inputAnswers(string given)
{
for (int n = 0; n < 10; n++)
{
cout << "Please enter your answer for question #" << n + 1 << " ";
cin >> given[n];
}
return given;
}
//Find if answers are correct or incorrect
int numCorrect(string correctAnswers, string given)
{
int numRight = 10;
int n = 0;
for (int n = 0; n < 10; n++);
{
if (given[n] != correctAnswers[n])
numRight -= 1;
}
return numRight;
}
The immediate issue is that given will start off as an empty string as you haven't assigned it a value:
cin >> given[n];
is causing the assert failure because you're trying to change the first (second, third etc) character in a string with a length of zero. To fix the assert problem (but not the program, which will always return 0%), just initialise the string:
string given = "ZZZZZZZZZZ";
To fix the rest of the stuff (btw this isn't the only way):
Change:
string inputAnswers(string given); //for both prototype and function.
to:
void inputAnswers(string& given); //pass by reference instead of pass by value.
//also get rid of "return given;"
Change:
int n = 0; //the n here is different to the one in the next line
for (int n = 0; n < 10; n++); //this n's scope begins and ends here thanks to the semicolon
{//the code here is executed once, this isn't in the loop!
if (given[n] != correctAnswers[n]) //we're using the first n here, which is 0.
numRight -= 1;
}
to:
for (int n = 0; n < 10; n++) //only one n variable and no semicolon
{// now this is in the loop and will execute 10 times.
if (given[n] != correctAnswers[n])
numRight -= 1;
}
Don't bother with this line:
int numRight = 0; //Set at 0 and then never changed.
and change:
numCorrect(correctAnswers, given);
to:
int numRight = numCorrect(correctAnswers, given); //declared when necessary and assigned the correct value
You either want to reserve enough space in your vector to hold 10 characters, or use push_back to populate the vector. Indexing a vector with [] won't grow the vector for you.
EDIT:
Ignore the first part about reserve. That doesn't stop the debug assertion. You will want to change this
cin >> given[n];
To something like this:
char input;
cin >> input;
given.push_back(input);

Error-correcting loop in C++, find specific chars in a string and flag as bad input

Here is v1.0 of the binary_to_decimal converter I wrote. I want to make several changes as I keep improving the spec. Classes and pointers will be added as well in the future. Just to keep me fresh and well practiced.
Well, I now want to implement an error-correcting loop that will flag any character that is not a 0 or a 1 and ask for input again.
I have been trying something along the line of this code block that worked with an array.
It might be way off but I think I can tweak it. I am still learning 0_0
I want to add something like this:
while ((cin >> strint).get())
{
cin.clear(); //reset the input
while (cin.get() != '\n') //clear all the way to the newline char
continue; //
cout << "Enter zeroes and/or ones only! \n";
}
Here is the final code without the error-correcting loop:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
const int MAX = 100;
int conv(int z[MAX], int l[MAX], int a);
int main()
{
int zelda[MAX];
int link[MAX];
string strint;
int am;
cout << "Enter a binary number: \n";
(cin >> strint).get(); //add error-correction to only read 0s and 1s.
am = strint.size();
cout << am << " digits entered." << endl;
int i = 0;
int p = 0;
while (i < am)
{
zelda[i] = strint[p] - '0'; //copies the string array elements into the int array; essentially STRING TO INT (the minus FORCES a conversion because it is arithmetic) <---- EXTREMELY CLEVER!
++i;
++p;
}
cout << conv(zelda, link, am);
cin.get();
return 0;
}
int conv(int zelda[MAX], int link[MAX], int length)
{
int sum = 0;
for (int t = 0; t < length; t++)
{
long int h, i;
for (int h = length - 1, i = 0; h >= 0; --h, ++i)
if (zelda[t] == 1)
link[h] = pow(2.0, i);
else
link[h] = 0;
sum += link[t];
}
return sum;
}
thanks guys.
I'm not completely sure of what you're trying to do, but I think what you're wanting is string::find_first_not_of. There's an example included in that link. You could have something like: myString.find_first_not_of("01");
If the return value is string::npos, then there are no characters in the string other than 1 or 0, therefore it's valid. If the return value is anything else, then prompt again for valid input and continue looping until the input's valid.