Error: comparison between signed and unsigned integer expressions? - c++

I'm getting this error on this line of code. Please help me solve it.
for (int i=0; i=((Main.size())-1); i++) {
Main code..
#include <istream>
#include <fstream>
#include <vector>
#include <algorithm>
#include "data.hpp"
using namespace std;
int main() {
vector<double> Main;
int count;
string lineData;
double tmp;
ifstream myfile ("sheffield.data", ios::in);
//double number;
myfile >> count;
for(int i = 0; i < count; i++) {
myfile >> tmp;
Main.push_back(tmp);
cout << count;
}
cout << "Numbers:\n";
cout << Main.size();
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
cin.get();
return 0;
}

The type of value returned by member function size is unsigned while i is declared as signed.
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
So instead of int i use at least unsigned int i or size_t i .It would be even better if you would use the type that is defined in class std::vector that is std::vector<double>::size_type i
Also in the condition part of the loop you are using the assignment operator = instead of the comparison operator == But if you would update the operator the condition will be wrong until size() will be equal to 0. Instead of operator == you have to use <=
The loop should look the following way
for ( std::vector<double>::size_type i = 0; i < Main.size(); i++ ) {
cout << Main[i] << '\n';
}
Also instead this for statement you could use the range based for statement that looks much simpler. For example
for ( double x : Main ) {
cout << x << '\n';
}

The i is of type int(signed) and the result of Main.size() of unsigned int, probably size_t depending on the tye of Main.
If you compare them in the for-loop, you have your explanation.
But be aware: a single = is an assignment, not a comparison.
Fix(probably):
for (unsigned int i=0; i < Main.size(); i++) {

You could also consider using iterators instead:
cout << "Numbers:\n";
cout << Main.size();
for (vector<double>::const_iterator i = Main.begin(); i != Main.end(); ++i) {
cout << *i << '\n';
}
(And as a side note, naming a variable (Main) with a capital letter is somewhat confusing!)

Related

How can I get around the use of VLAs?

I have made some code and need to make the length of an array the same as a user input:
#include <iostream>
#include <string>
using namespace std;
void abrev(string word) {
int lastChar = word.length();
if (lastChar > 10) {
cout << word[0];
cout << lastChar - 2;
cout << word[lastChar - 1] << endl;
} else {
cout << word << endl;
}
}
int main() {
int n;
cin >> n;
string words[n];
for (int i = 0; i <= n - 1; i++) {
cin >> words[i];
}
for (int i = 0; i <= n - 1; i++) {
abrev(words[i]);
}
return 0;
}
I don't really know what I could possibly do, I have no ideas. I was using a compiler that just side steps this problem, so I didn't realize it until I submitted this code to codeforces.com, in which I got these errors:
Can't compile file:
program.cpp
program.cpp(20): error C2131: expression did not evaluate to a constant
program.cpp(20): note: failure was caused by a read of a variable outside its lifetime
program.cpp(20): note: see usage of 'n'
program.cpp(23): warning C4552: '>>': operator has no effect; expected operator with side-effect
Also I don't think the last error has anything to do with it, if you could help with that to that would be awesome!
Thankful for any help!
It's mostly duplicated, to resolve the error, it's easy to fix it with std::vector
Since the function abrev doesn't change the argument, it's better to use a const reference.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void abrev(const string& word) {
int lastChar = word.length();
if (lastChar > 10) {
cout << word[0];
cout << lastChar - 2;
cout << word[lastChar - 1] << endl;
} else {
cout << word << endl;
}
}
int main() {
int n;
cin >> n;
std::vector<std::string> words(n);
for (int i = 0; i <= n - 1; i++) {
cin >> words[i];
}
for (int i = 0; i <= n - 1; i++) {
abrev(words[i]);
}
return 0;
}

Why is it not working?

I want to create a program that will transform the same words into one. I have a problem with code where I used "while". If I put "if" instead of "while" its working, but not as right as I want, so I need to use "while", but its not working correctly. Its compiling, but not working after inputting the string a.
#include <iostream>
using namespace std;
int main ( ) {
string a;
cout << "Введите string a: ";
getline(cin,a);
for (int i = 0; i < a.length(); i++) {
while (a[i]=a[i+1]) {
for (int z = i; z < a.length(); z++) {
a[z]=a[z+1];
}
}
}
cout << endl << a << endl;
}
while (a[i]=a[i+1]) {
you probably mean
while (a[i]==a[i+1]) {
= is assignment; == is comparison.
When compilomg, pass -Wall to get warnings about this sort of thing. (If a microsoft compiler turning warnings on may require something different; for other compilers, -Wall means "turn on warnings: all normal ones").
Even when I replaced while with if it still wasn't working as you intended. I'm more surprised that you're able to use getline without the string header. You're also assigning the previous character of string a to the next character of a.
Please try this:
#include <iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> dupes;
string word;
string a;
cout<<"Enter line:";
getline(cin , a);
int i = 0; //the counter
while(i <= a.length()) {
if(!isspace(a[i])) {
word += a[i];
} if(isspace(a[i])) {
bool present = (find(dupes.begin() , dupes.end() , word) != dupes.end());
if(!present) {
dupes.push_back(word);
word = "";
}
word = "";
}
++i;
}
}
Try your best to avoid nesting loops into one another when possible.
I solved it!
#include <iostream>
using namespace std;
int main ( ) {
setlocale(LC_ALL,"Russian");
cout << "Сборник задач: 7.2" << "\nLv Easy" << "\nExercise #02" << endl << endl;
string a;
cout << "Enter a line: ";
getline(cin,a);
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < a.length(); j++) {
if (a[i]==a[i+1]) {
for (int z = i; z < a.length(); z++)
a[z]=a[z+1]; } } }
cout << endl << a << endl << endl;
}

Multidimensional array prints hexadecimal numbers instead of the contents of the array. Why?

...C++.....................
#include <iostream>
using namespace std;
int main() {
int troysArray[3][3] = {
{3,2,7},
{4,5,8},
{1,9,2},
};
int i;
int j;
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++){
cout << troysArray[i] << endl;
cout << troysArray[j] << endl;
};
return 0;
}
.......................
C++
Why does the above code print out hex numbers when I'm actually trying to print out the contents of the array. (Beginner/Just practicing)
What am I doing wrong that's causing this to occur?
The best overload of the std::ostream << operator for troysArray[i] is void* (exploiting pointer decay), and that outputs the address of the pointer.
If you want an element use troysArray[i][j] &c.
troysArray[i] and troysArray[j] are pointers to an array. If you want to print element at i and j, use
cout << troysArray[i][j] << endl;
troysArray is an array of arrays of int.
Thus, troysArray[i] is an array of int, and so is troysArray[j].
There is no overload of operator << for array of int.
However, there is one for void*.
When you pass an array as an argument, what actually gets passed is a pointer to the array's first element.
(In your case, those are &troysArray[i][0] and &troysArray[j][0], both of type int*.)
An int* can be implicitly converted to void*, so the operator << for void* can be used.
This overload outputs the value of the pointer in hexadecimal form.
In order to print the ints you need to print the elements j of each array troysArray[i]:
cout << troysArray[i][j] << endl;
To print it more "matrix-like", with each row on its own line:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << troysArray[i][j] << ' ';
}
cout << endl;
}
To print out the contents of the table in a grid (as asked in one of the comments on Guarev Senghai's answer:
#include <iostream>
using namespace std;
int main() {
int troysArray[3][3] = {
{3,2,7},
{4,5,8},
{1,9,2},
};
int i;
int j;
for (i = 0;i < 3;i++)
{
for (j = 0;j < 3;j++)
{
cout << troysArray[i][j];
//uncomment the next line to have a spaces between the numbers.
cout << " ";
}
cout << endl;
}
return 0;
}

C++ array size by user input

I'm trying to write a program that will have a user input size for an array, and then take values into that array. I initially tried
int sz = 51;
double Arr[sz];
Which led to compilation errors. Apparently dynamic allocation of the variable has to happen, and I'd rather avoid that if possible. So I modified my code (current state as shown below) which now only throws "expected primary-expression before ']' token". Is there a way to fix this and I'm just not seeing it, or do I need to use dynamic allocation?
Thanks for your time!
#include <iostream>
#include <iomanip> //for setprecision
using namespace std;
int sz = 51;
double n=0;
double Arr[0];
void get_input(double Arr[], int &sz){ //gets input
do{
cout<< "Enter size: "<< endl;
cin>> sz;
if (sz<0 || sz>50){
cout<< "Invalid size, enter a value between 0 and 50"<<endl;
}
}while(sz<0 || sz>50);
for( int i=0; i<sz; i++){
cin>> Arr[i];
}
}
double calcSum( double Arr[], int sz){ //finds sum
for(int i=0; i<sz; i++){
n+= Arr[i];
}
return(n);
}
void printArray(double Arr[], int sz){ //prints array elements
for(int i=0; i<sz; i++){
cout<< Arr[i]<< setprecision(2)<<" ";
if(i%7 == 0)
cout<< endl;
}
}
int main()
{
double Arr[sz];
get_input(Arr[], sz); //error here
printArray(Arr[], sz); //error here
return 0;
}
VLAs (e.g. Arr[sz]) are only supported as extensions in C++. They aren't part of the official language standard. You should use std::vector instead.
Just use a std::vector, there's a standard library in C++ for this reason.
Demo:
notes: you don't need the globals (they are shadowed by the locals and you pass them by reference anyways)
Live On Coliru
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
using array_t = std::vector<double>;
void get_input(array_t& Arr) { // gets input
size_t sz = 51; // unsigned types cannot be negative
do {
cout << "Enter size: " << endl;
cin >> sz;
if (sz > 50) {
cout << "Invalid size, enter a value between 0 and 50" << endl;
}
} while (sz > 50);
for (size_t i = 0; i < sz; ++i) {
double v;
if (cin >> v)
Arr.push_back(v);
else
std::cerr << "Error reading input\n";
}
//assert(sz = Arr.size());
}
double calcSum(array_t const& Arr) { // finds sum
double n = 0;
for (size_t i = 0; i < Arr.size(); ++i) {
n += Arr[i];
}
return n;
}
void printArray(array_t const& Arr) { // prints array elements
for (size_t i = 0; i < Arr.size(); ++i) {
cout << Arr[i] << setprecision(2) << " ";
if (i % 7 == 6)
cout << endl;
}
}
int main() {
array_t Arr;
get_input(Arr);
printArray(Arr);
std::cout << "\nSum: " << calcSum(Arr) << "\n";
}
When entering 3 1 2 3 you get:
Enter size: 3
1 2 3
1 2 3
Sum: 6

Dynamic arrays with C++

my question refers to dynamic arrays in C++. I'm new at the language so please spell things out for me where possible.
I was wondering how I could change the following code to accept floats?
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length;
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
int *dArray;
dArray = new int[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
for ( int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
delete[] dArray;
return 0;
Here's a more safe and easy way to write that code:
#include <iostream>
#include <vector> // std::vector
using namespace std;
int main()
{
int length;
cout << "Please enter the length of the array: ";
cin >> length;
vector<int> dArray( length );
for( int i = 0; i < length; ++i )
{
dArray[i] = i;
}
for( int i = 0; i < length; ++i )
{
cout << dArray[i] << " ";
}
}
The basic floating point type in C++ is called double. E.g. the literal 3.14 is of type double. So you can use that instead of int for the array item type.