C++ with #include<string> and getting C2679 - c++

Thank you to #crashmstr for triggering the right brain cells to work. My problem is that you can't have an integer written into an array with that format.
cin>>votes[a][0]; was the right answer to the problem.
#include<iostream>
#include<iomanip>
#include<istream>
#include<string>
using namespace std;
const int nameRow = 6, nameCol = 7, voteRow = 6, voteCol = 2;
int main ( )
{
char candName[nameRow][nameCol];
int votes[voteRow][voteCol];
for(int a=0;a< nameRow;a++)
for (int b = 0; b < nameCol;b++)
candName[a][b] = 0;
for (int c = 0; c < voteRow;c++)
for (int d = 0; d < voteCol;d++)
votes[c][d] = 0;
cout << "Enter a candidate's name : ";
for (int a = 0;a < nameRow;a++)
{
cin >> candName[a], nameCol;
cin >> votes[a], voteCol;
}
system ( "pause" );
}
My problem is the last cin of the file. The >> is getting the code. It doesn't matter if I put it in the same line, another loop, same function different loops or different functions all together the >> of that line is tripping C2679.
The most popular fix I have seen is having #include<string.h>and changing that to <string>. I didn't initially have it but I added it when I saw it but it hasn't fixed anything.
Can anyone give me some insight of what I am missing?
Error message:
binary '>>' : no operator found which takes a right-hand operand of type 'int[2]' (or there is no acceptable conversion)

Using #include <string> is part of a solution but you forgot to actually use the string type. Also you use a lot of antique stuff. The code could look like:
#include<iostream>
#include<iomanip>
#include<string>
const int numRows = 6;
int main ( )
{
std::string candName[numRows]; // empty strings
int votes[numRows] {}; // zero-initialized
for (int a = 0;a < numRows;a++)
{
std::cout << "Enter a candidate's name : ";
std::cin >> candName[a] >> votes[a];
if ( ! std::cin )
break; // stop if they type something bad
}
}
Another easy modification to make would be to store the results in a vector of user-defined type containing string and int , instead of having two fixed-size arrays. Then you can accept any number of inputs instead of exactly 6 .

This needs fixing, replace , with >> or something:
for (int a = 0;a < nameRow;a++)
{
cin >> candName[a], nameCol; // << -- here
cin >> votes[a], voteCol; // << -- and here
}
And this is a very bad style:
for (int c = 0; c < voteRow;c++)
for (int d = 0; d < voteCol;d++)
votes[c][d] = 0;
Please, add curly brackets like this:
for (int c = 0; c < voteRow;c++) {
for (int d = 0; d < voteCol;d++) {
votes[c][d] = 0;
}
}

Related

Convert userInput (string) to UserInput(int) mid for loop

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

did in i need in my c++ code to use vectors or learn STL

i need to initialize my code during runtime the program is searching for how many times is the number in multiplication table
#include <iostream>
using namespace std;
int main()
{
int x = 0, n = 1 , count=0 ;
cin >> n>>x;
int arr[n][n];
for (int i = 0; i <n-1 ; i++) {
for (int j = 0; j <n-1 ; j++) {
cin >> arr[i][j];
if(arr[i][j]==x)count++;
}
}
cout<<count;
}
because i am getting error
did in i need in my c++ code to use vectors or learn STL?
The answer depends on your objective.
If you want to accomplish a programming task at hand in the most expedient manner, use std::vector.
If you want to learn how to manage allocation and dealloction of dynamic memory, learn about new and delete and use them instead of int arr[n][n];
I think by multiplication table you mean to say matrix.
For this particular problem you don't need even the matrix. You can just do by using a temporary variable. Something like this:
#include <iostream>
int main() {
int n, x, count = 0, tmep;
std::cin >> n >> x;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
std::cin >> temp;
if (temp == x) ++count;
}
std::cout << count;
}
You aren't getting proper answer probably because you are not reading the complete matrix. Your loops run from i = 0 to i < n - 1 (same for j). You need to either change < to <= or n - 1 to n.
If you need to re-use the inputted matrix, then probably an approach like this will be good:
#include <iostream>
#include <vector>
int main() {
int n, x, count = 0;
std::cin >> n >> x;
std::vector<std::vector<int>> mat(n, std::vector<int>(n));
for (auto &row : mat)
for (auto &ele : row) {
std::cin >> ele;
if (ele == x) ++count;
}
std::cout << count;
}
In any case something like arr[n][n] is not recommended as variable-length arrays are not supported by the standard itself, although some compilers like g++ do so.

Right way of using max function and/or alternatives

So, here is my homework problem. It states "Enter five numbers five times. Every time, the program chooses the biggest number you enter, and it returns the arithmetic mean of those five largest numbers." Now, what I've done is use max function, however, I learned that it isn't useable in this way. Here is what I've tried:
#include <iostream>
using namespace std;
int main() {
int zbir = 0;
for (int i = 1; i < 6; i++) {
int a, b, c, d, e;
for (int j = 1; j < 6; j++) {
cin >> a >> b >> c >> d >> e;
}
int maks = max(a, b, c, d, e);
zbir = zbir + maks;
}
cout << zbir / 5;
}
There are two versions of max: the two-argument version, and the initializer list version. In this case, you have five arguments, so use the initializer list version:
std::max({a, b, c, d, e})
(You need to #include <algorithm> to use std::max.)
Within your code you do not need to have an inner for-loop because you are already collecting all 5 of the user numbers with the cin >> a >> b >> c >> d >> e; statement. Having a second for loop around it will cause you to collect 5 numbers from the user 25 times total.
This is an example of the alternative to using the max function in which case a single number is collected 5 times making use of an inner for-loop:
int main()
{
int sumOfMaxNums = 0;
int userNum = 0;
int maxNum = 0;
// it is a good practice to have a const that will bound the loop
// this way you can change it from here
// in other cases you can have two different const bounds, one for the inner loop and
// one for the outer loop because they may differ
const int NUM_ITERS = 5;
// This will handle asking the user to enter the numbers 5 times
for(int i = 0; i < NUM_ITERS; ++i)
{
// this loop will asks the user to enter a number 5 times and keep track of the max
for(int j = 0; j < NUM_ITERS; ++j)
{
cin >> userNum;
// here we want to set the maxNum to be the very first number that the user enters
// or we could set it to smallest negative number
if(j == 0)
{
maxNum = userNum;
}
else if(userNum > maxNum)
{
maxNum = userNum;
}
} // end of inner for-loop
sumOfMaxNums += maxNum;
} // end of outer for-loop
cout << sumOfMaxNums / static_cast<float>(NUM_ITERS) << "\n";
} // end of main
You probably want to calculate the mean as a float rather than an int, otherwise the program will round the final answer down to the nearest whole number. Also, you really don't need to use five variables to store each cycle's inputs, since you can ignore any inputs that are less than the running maximum for that cycle. This means you don't need to use std::max at all.
#include<iostream>
int main()
{
float running_total = 0;
for (int cycle = 1; cycle < 6; ++cycle)
{
float cycle_max;
for (int entry = 1; entry < 6; ++entry)
{
float input = 0;
std::cin >> input;
if (entry == 1 || input > cycle_max) cycle_max = input;
}
running_total += cycle_max;
}
std::cout << running_total / 5 << std::endl;
}

C++ determinable array input in one line

I'm pretty new to c++ and can't seem to find correct way to code this. I have array of n digits, my code now:
int main()
{
int n,i;
cin >> n;
int a[n];
for (i=1;i<=n;i++)
{
cin >> a[i];
}
return 0;
}
This way every element of array has to be input in different line, is it possible to put all elements of a array in one line, with space between them.
I am assuming your question is "what is the correct way to do this?"
I would do it this way:
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
int n;
cin >> n;
vector<int> v;
int i = 0;
int value;
while (i++ < n && cin >> value)
{
v.push_back(value);
}
char const* sep = "";
for (auto item : v)
{
cout << sep << item;
sep = " ";
}
cout << endl;
}
Note that this code is making assumptions that the input is well formed. If you need something that is more robust in handling possibly malicious input, that would require extra effort. This code, as given, will give-up-trying-and-continue which may or may not be suitable for your purposes.
The following code snippet of your program is a Variable Length Array(VLA) and this is only supported in C since ISO C99.
cin >> n;
int a[n];
And as previously pointed out, you can also use std::vector instead.
int main()
{
int size;
std::cin >> size;
int *array = new int[size];
delete [] array;
return 0;
}
References:
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
How to create a dynamic array of integers
Without using stl container , one can implement like so:
#include <iostream>
#include <string>
#include "stdlib.h"
void GetInput(int* inputs, int n)
{
// store the entered numbers in a char[]
std::string word;
std::cout << "enter numbers (separate by space) ";
std::getline(std::cin, word);
char ch[100];
strcpy_s(ch, word.c_str());
char *temp = ch;
// parse the char[] for integers
for (int i = 0; strcmpi(temp, "") != 0 && i <= n; temp++,i++) {
*(inputs +i) = std::strtol(temp, &temp, 10);
}
}
int main()
{
int n = 3;
int inputs[10];
GetInput(inputs,n);
for (int j = 0; j < n; j++)
std::cout << inputs[j] << " \n";
return 0;
}
Output:

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.