Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have an array of characters with variable size which is received from user input. From there I input the array with for loop based on the size but it seems like the variable holding the size is changing and I'm stuck in infinite loop.
char arr_1[] = {};
int array_size;
cout << "Array size: ";
cin >> array_size;
for (int i = 0; i < array_size; i++)
{
cout << "Input: ";
cin >> arr_1[i];
}
I have an array of characters with variable size
char arr_1[] = {};
There is no such thing as "array with variable size" in C++. The size of an array never changes. Furthermore the size of non-dynamic arrays must be compile time constant. What you have declared there is an array of size zero. Non-dynamic arrays of zero size are ill-formed.
If the compiler for some reason fails to spot the bug (perhaps it supports zero length arrays as a language extension), then you end up accessing the array outside of bounds. The behaviour of accessing an array out of bounds is undefined. Infinite loop is one example of undefined behaviour.
There is however a standard container that will automatically reallocate a progressively larger array as you insert elements into it: std::vector.
Although, since you're dealing with characters, perhaps they're supposed to represent a character string. There is a special container for that purpose: std::string.
Vector would be more appropriate to use than an array in this case. Even easier is to just work with a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numChars = 0;
string word("");
cout << "Num chars you want to input: ";
cin >> numChars;
for (int i = 0; i != numChars; ++i)
{
string input("");
cout << "Enter a char: ";
cin >> input;
if (input.size() == 1)
word += input;
else
{
cout << "Invalid input- exiting";
getchar();
exit(0);
}
}
cout << "Your word: " << word;
getchar();
getchar();
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 months ago.
Improve this question
I am a beginner, and I am trying to learn C++.
For now, all I am trying to do is input 3 numbers, and print them back.
#include <iostream>
using namespace std;
int main(){
int n[2];
cout << "Enter three numbers" << endl;
for (int j = 0; j <= 2; j++){
cin >> n[j];
}
cout << "Debug " << n[2] << endl;
cout << endl;
for (int i = 0; i <= 2; i++){
cout << n[i] << "\t" << i << endl;
}
return 0;
}
Every time I print them, the last value of the array is modified, and I cannot figure out why! For a test input 6,7,8, the output is in the image below.
This for
for (int j=0;j<=2;j++){
cin>>n[j];
}
expects that the array has at least three elements with indices in the range [0, 2].
However you declared an array with two elements
int n[2];
If you are going to input three elements then the array should be defined as
int n[3];
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
#include <iostream>
using namespace std;
int main(){
int howMany, num[howMany], max; //defining variables
cout<<"How many numbers do you want to add? (Enter your number and press enter): ";
cin>>howMany;
for(int i=1;i<=howMany;++i){
cout<<"Enter you number: ";
cin>>num[i-1];
}
max=num[0];
for (int element:num){
max=(max>=element)?max:element;
}
return 0;
}
well i actually wanted to find the largest number out of a given set of numbers....
i wanted to take an input from a user on how many numbers he wants to add. then i take all those numbers, for that i made a loop. and then i compare each element of that array of numbers with the previous one to find the largest number. i compiled my code, received no errors....and then when i run it i get an empty output. like this:my output img. please help me out!!!
You declared a variable length array num
int howMany, num[howMany], max; //defining variables
Variable length arrays is not a standard C++ feature.
Moreover in the declaration you are using an uninitialized variable howMany. So the program has undefined behavior.
Instead of the variable length array you could use the standard container std::vector<int>.
Pay attention to that there is standard algorithm std::max_element in C++ that allows to find the maximum element in an array.
Here is a demonstration program.
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t howMany = 0;
std::cout << "How many numbers do you want to add? (Enter your number and press enter): ";
std::cin >> howMany;
std::vector<int> num( howMany );
for ( size_t i = 0; i < howMany; ++i )
{
std::cout << "Enter you number: ";
std::cin >> num[i];
}
auto it = std::max_element( std::begin( num ), std::end( num ) );
if (it != std::end( num ))
{
std::cout << "The maximum value is " << *it << '\n';
}
}
There are 2 problems with your program.
Mistake 1
You didn't initialize the variable howMany. This means it holds an indeterminate value. And using this uninitialized variable as you did when you wrote num[howMany] leads to undefined behavior.
Undefined behavior means anything can happen including but not limited to program being successfully compiled and giving your expected output. But don't rely on the output of a program that has undefined behavior.
For more reading(technical definition of) on undefined behavior you can refer to undefined behavior's documentation which mentions:
there are no restrictions on the behavior of the program.
This is why it is advised that
Always initialize built in types in local/block scope.
Mistake 2
In Standard C++ the size of an array must be a compile-time constant. So for example, consider the following examples:
int n = 10;
int arr[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Similarly, in your code,
int howMany, num[howMany]; //INCORRECT because howMany is not a constant expression
Solution
You can solve this by using a std::vector as shown below:
#include <iostream>
#include <vector>
int main(){
int howMany = 0, max = 0; //defining variables
std::cout<<"How many numbers do you want to add? (Enter your number and press enter): ";
std::cin>>howMany;
//create a vector of size howMany
std::vector<int> num(howMany);
//iterate and take input from user
for(int &elem: num){
std::cout<<"Enter you number: ";
std::cin>>elem;
}
max=num.at(0);
for (int i = 1; i < num.size(); ++i){
if(num[i] > max)
{
max = num[i];
}
}
std::cout<<"biggest number is: "<<max;
return 0;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have searched on this a lot, and have not found any satisfactory response. I am codding a small mathematical algorithm in order to learn a few programming languages, and as such, this is part of my first C++ program. However, I can't seem to fix this array. Although people say random values in arrays are due to the arrays being uninitialized, and that you should initialize them to the value you want like so: int array[sizeOf] = {0}, it only sort of works in this example. Here as you can see, all values of the array get set to 0, exept the very last one, which does not seem to be getting initialized: what is causing this, and how can I fix it?
#include <iostream>
using namespace std;
int initialNumber;
int main()
{
cout << "Enter Range value:" << endl;
cin >> initialNumber; //get size
cout << "Solving..." << endl << endl;
//initialize basic ints to be used for calculations
int limiter = initialNumber/2; //the max value we will ever have to multiply by
int arraySize = initialNumber++; //size of the array
int resultingFactorsArray[arraySize] = {0}; //main array
//print each array item value
for (int x = 0; x <= arraySize; x++) {
cout << resultingFactorsArray[x] << endl; //print all array values
//all values printed should be 0, but the last one is uninitialized
}
}
Arrays are 0 based. Meaning, in your for loop, for (int x = 0; x <= arraySize; x++), the part x <= arraySize should be x < arraySize.
An example:
If you declare your array size 10, the valid array indices are 0,1,2,3,4,5,6,7,8,9 (10 total indices).
If you were to throw that in a for loop with x <= 10, your last index would be array[10] (undefined/uninitialized).
So in short, your initialization is correct, it just that your for loop is going out of bounds.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used std::sort function .but it's not working.
here is my code
#include <bits/stdc++.h>
using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
{
cin>>n;
cin>>str;
low[0]='\0';
upr[0]='\0';
int i=0,j=0,k=0;
while(i<n)
{
(str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
++i;
}
low[j]='\0';
upr[k]='\0';
cout<<"lowercase="<<low<<'\n';
cout<<"uppercase="<<upr<<'\n';
sort(low,low+j);
sort(upr,upr+k);
cout<<"lowercase="<<low<<'\n';
cout<<"uppercase="<<upr<<'\n';
}
return 0;
}
test case:
1 // number of test cases
15 // length of string
abHJUdjKIpwlaKm
output:
lowercase=abdjpw //before sorting
uppercase=HJUKIK //before sorting
lowercase=abdjpw //after sorting
uppercase= //after sorting
after sorting uppercase string don't even print.
You have a bug with indexes, fix:
low[k] = '\0';
upr[j] = '\0';
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
sort(low, low + k);
sort(upr, upr + j);
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
Exchanged k and j in this snippet.
Better variable names would help. Try replacing j and k with something more descriptive like lowIndex and uprIndex. Then you should see the problem.
I noticed you were using j variable for uppercase and k for lowercase in the while loop then proceeded to do the opposite later. Was this intentional? Wondering if that's causing a bug.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
int main()
{
vector<int>numbers;
int numb = 0;
int i = 0;
int j = i - 1;
while (cin >> numb)
{
if (numb == numbers[j]) HERE IS THE PROBLEM!*
{
cout << "Numbers repeated\n";
}
numbers.push_back(numb);
cout << "numbers[" << i << "] = " << numbers[i] << endl;
++i;
}
/*** I don't understand why a exception, run time error, break or whatever it names.....................................................
On the first iteration through the loop, j is -1. Accessing numbers[-1] is undefined behavior because the index is outside the bounds of the vector.
Indeed, accessing any index is out of bounds until you put something in the vector, so you cannot index numbers at all until you have called push_back on it at least once.
This code will display the message if the user enters a number already in the vector:
while (cin >> numb) {
vector<int>::iterator found = std::find(numbers.begin(), numbers.end(), numb);
if (found == numbers.end()) {
cout << "Numbers repeated" << endl;
}
// If you don't want duplicate numbers in the vector, move this statement
// into an "else" block on the last "if" block.
numbers.push_back(numb);
}
This code on the other hand will only display the message when a number was the same as the last number entered, that is, if sequential numbers are the same:
while (cin >> numb) {
if (!numbers.empty() && numb == numbers.back()) {
cout << "Numbers repeated" << endl;
}
numbers.push_back(numb);
}
You need to initialize your numbers vector with initial data, or check to make sure j is withing in vector size. A vector is essentially an array, and like any array, you cannot go out of bounds.
if (j < numbers.size() && numb == numbers[j]) HERE IS THE PROBLEM!*
{
cout << "Numbers repeated\n";
}