c++ vector : initializing with cin in a loop [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 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
I'm new to programming and i have problem with some items
i would appreciate any help
first i started initializing the vector as followed but i couldn't end the loop with Ctrl+Z
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector <double> temps;
double temp;
cout << "Enter a sequence of tempreatures : " << "\n" ;
while (cin >> temp){
temps.push_back(temp);
}
double sum = 0;
for (int i = 0; i< temps.size(); ++i)
sum += temps[i];
cout << "Mean temprature : " << sum / temps.size() << "\n";
sort(temps.begin(), temps.end());
cout << "Median temprature : " << temps[temps.size() / 2];
then i changed the while into this format :
cout << "ENter a sequence of tempreatures ending in 1500 : " << "\n" ;
while (cin >> temp){
if (temp == 1500)
break;
temps.push_back(temp);
}
now i have this error
"vector subscript out of range"
apparently break does not work properly here
what should i do?

Your issue is in the check condition of for loop.
for (int i = 0; i, temps.size(); ++i)
sum += temps[i];
It should be
for (int i = 0; i < temps.size(); ++i)
i, temps.size() will evaluate and then ignore the part before , and are left with temps.size() as check condition which will always be greater than 0 if you push_back at least one element and your loop will never end.You might want to read how ,(comma) works.

If you switch to std::getline into a string instead of std::cin into a double, you can check whether the input is empty:
std::string input;
std::getline(std::cin, input);
while (!input.empty()){
temps.push_back(atof(input.c_str()));
std::getline(std::cin, input);
}
If you also fix the for-loop as mentioned by Gaurav Sehgal, it works fine (Enter all numbers then hit enter without any input).

If you are on windows then you have to do
CTRL + Z
If you are on Unix based(Linux/Mac) then you have to do
CTRL + D
This will give the end of file signal and you will be able to break the loop

Related

Garbage value in an array where array length and input is defined [closed]

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];

C++ Can't use vector and string literal in cout [closed]

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'm a student who just learned to use C++ for a few weeks. I write C++ code on Code:: Block and I am trying to run this code to learn about vector:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> intVector;
for(int i = 0; i < 10; i++)
{
intVector.push_back(i+1);
}
cout << "Numbers in vector: ";
for(int i = 0; i < intVector.size(); i++)
{
cout << intVector[i] + " ";
}
}
But the output is really weird:
Numbers in vector: vector::_M_emplace_back_auxector::_M_emplace_back_auxctor::_M_emplace_back_auxtor::_M_emplace_back_auxor::_M_emplace_back_auxr::_M_emplace_back_aux::_M_emplace_back_aux:_M_emplace_back_aux_M_emplace_back_aux
Process returned 0 (0x0) execution time : 0.047 s
Press any key to continue.
Does anyone know how to fix this problem? Do I use vector in the wrong way?
Try changing the cout line like this:
cout << intVector[i] << " ";
What you're trying to do is add an int& and a string literal -- in some compilers it will emit a warning indicating for you that you're not getting what you intended for.
For example with Clang:
warning: adding '__gnu_cxx::__alloc_traits>::value_type' (aka 'int') to a string does not append to the string [-Wstring-plus-int]
cout << intVector[i] + " ";
~~~~~~~~~~~~~^~~~~

std::sort function not working in char array [closed]

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.

If inside while error [closed]

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";
}

C++ Prime Number not giving the correct answer [closed]

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 9 years ago.
Improve this question
#include <iostream>
#include <cmath>
using namespace std;
bool prime(int n);
int main()
{
double i;
while (true)
{
cout << "Enter a number that isn't 0: ";
cin >> i;
if ( i == 0)
break;
if(prime(i))
cout << i << " is prime" << endl;
else
cout << i << " is not prime." << endl;
}
system ("Pause");
return 0;
}
bool prime (int n)
{
int i;
double sqrt_of_n = sqrt(double (n));
for (i = 2; i <= sqrt_of_n; i++)
{
if (int(n) % 1 == 0)
return false;
}
return true;
}
Everytime I run the program, if I input 7, I get that 7 isn't prime. Can someone help me figure out where I messed up?
I have tried changing between double and int for i and n.
If I input 3, it shows prime.
The problem is that it's showing some prime numbers as not prime.
The body of your for loop doesn't use i at all.
In particular, n % 1 is always zero, for any integral n.
Presumably you want to know whether n is divisible by i, but accidentally checked if n is divisible by 1.
You could easily have discovered this mistake yourself by single-stepping in a debugger, and making the various subexpressions into "watch expressions".