I am trying to return long int from a function but it is not working at all, then I tried to print a long int number to the screen and still not working.
#include<iostream>
using namespace std;
long int maximum_product(long int *input_array, int n){
long int a,b;
a = *input_array;
b = *(input_array + 1);
if (b > a){
long int temp = a;
a = b;
b = temp;
}
for (int i = 2; i < n; i++){
if (input_array[i] > b){
if(input_array[i] > a){
b = a;
a = input_array[i];
} else
b = input_array[i];
}
}
return a * b;
}
int main(){
int n;
cin >>n;
long int *input_array = new long int[n];
for (int i = 0; i < n; i++)
cin >> input_array[i];
cout << maximum_product(input_array, n);
return 0;
}
Here is what I mean by "not working":
#include<iostream>
using namespace std;
int main(){
long int y;
cin >>y;
cout<<y;
return 0;
}
Result of the second program
If you want to make std::cin read
2,147,483,646
as a long you need to do a little bit extra, because without you std::cin will only read the first 2 and ignore the rest.
Lets start simple....std::cin has an overload of its operator>> for long but we want it to do something else. How do we make it pick a different overload? We pass a different type. However, as we dont actually want anything else than a long we use a thin wrapper:
struct read_long_with_comma_simple_ref {
long& long;
read_long_with_comma_simple_ref(long& value) : value(value) {}
};
Once we supply our own operator>> overload we will be able to write something like this:
long x;
std::cin >> read_long_with_comma_simple_ref(x);
So far so simple. How can we implement that operator>>? The most simple I can think of is to simply ignore the commas:
std::istream& operator>>(std::istream& in,read_long_with_comma_simple_ref& ref) {
std::string temp;
// read till white space or new-line
in >> temp;
// remove all commas
temp.erase(std::remove(temp.begin(), temp.end(), ','), temp.end());
// use a stringstream to convert to number
std::stringstream ss(temp);
ss >> rwcs.value;
return in;
}
However, this will accept non-sense such as 12,,,34 as input and interpret it as 1234. This we of course want to avoid and add a bit of error checking:
#include <iostream>
#include <limits>
#include <algorithm>
#include <sstream>
#include <ios>
// same as before, just different name for a different type
struct read_long_with_comma_ref {
long& long;
read_long_with_comma_ref(long& value) : value(value) {}
};
std::istream& operator>>(std::istream& in,read_long_with_comma_ref&& rwc){
std::string temp;
in >> temp;
std::reverse(temp.begin(),temp.end());
std::stringstream ss(temp);
rwc.value = 0;
long factor = 1;
for (int i=0;i<temp.size();++i){
char digit;
ss >> digit;
if (((i+1)%4)==0) {
if (digit != ',') {
in.setstate(std::ios::failbit);
rwc.value = 0;
return in;
}
} else {
int dig = digit - '0';
if (dig < 0 || dig > 9) {
in.setstate(std::ios::failbit);
rwc.value = 0;
return in;
}
rwc.value += factor* (digit-'0');
factor*=10;
}
}
return in;
}
And we can use it like this:
long x;
std::cin >> read_long_with_comma_ref(x);
if (std::cin.fail()) std::cout << "reading number failed \n";
std::cout << x;
TL;DR if you want to make std::cin read the value 2147483646 then simply type 2147483646 and dont use the , as seperator, or read it as string and remove the commas before converting it to a number.
Related
I'm new to programming, and I'm wondering, how can I know the number of digits in an integer that the user enters? For example: the user enters a number like 123456, how can I know that the user enters 6 digits? I don't want to use a for loop to get user input because I don't want the user to enter each digit after a space or enter.
Right now, I'm converting a number to an array of digits so I can have control over them, but the issue is that I don't know how many digits I should loop over, because I don't know how many digits are in the number.
Can I get the user's input as a string and then use string.length and convert it to an array of digits?
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
while(N--)
{
int num;
cin >> num;
int arr[1000];
for (int i=0 ;i<???;i++)
{
arr.[i]=num%10;
num = num /10;
}
}
}
an easier way to do this is to convert it to a string then count the length of said string
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string str = to_string(n);
cout <<"the length of" <<str << "is:" <<str.length() <<"\n";
}
typing in a 41 will print out.
the length of 41 is 2
while (num != 0)
{
arr.[i]=num%10;
num = num /10;
}
is a common pattern that's close to what you already have.
Although you can do what you mentioned in your question and someone suggested in the comments and get the input as a string and use string.length.
Yes, you can read in the user's input as a std::string instead of as an int, and then you can use std::string::size() (or std::string::length()) to get the number of characters in the string, eg:
#include <iostream>
#include <string>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Either way, if needed, you can check if the std::string represents a valid integer using std::stoi() or std::strtol() or other similar function, or by putting the std::string into a std::istringstream and then reading an integer from it.
Otherwise, you can read the user's input as an int and then convert it to a std::string for processing:
#include <iostream>
#include <string>
int main()
{
unsigned int N;
std::cin >> N;
std::string S = std::to_string(N);
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
// or:
// std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Otherwise, if you really want to read in an int and loop through its digits directly, you can use something more like this:
#include <iostream>
int main()
{
unsigned int N;
std::cin >> N;
int arr[1000] = {};
size_t i = 0;
while (N != 0)
{
arr[i++] = num % 10;
num /= 10;
}
return 0;
}
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:
I know that you probably gona again vote me down, I really don't understand this but im really stuck at something and cant figure it out , there is no such information anywhere in the web , neither in my book for the course, so I have this assignment where I need make 2 sums of containers where the difference between 2 sums is the lowest , so the program is done is working perfectly calculated everything however , in my assignment:
The user enter on one row unkwonw length numbers so after that I do all kind of sums between them and find the one with lowest difference between.
Ok but the way I wrote the code I use one while(true) so that to work with infinity testcases(as from assignment) and in this while(true) I have another while(cin>>(SOMEINT)) loop and push it back in a vector , and after it reads new line it just break the wile and continue with the calculation.
However in our test software this one give runtime error since after finding some cases then it start print infinity 0 0 since there is nothing to enter but the while(true) just continues.
I mean I just want to make it that way that the while is till user enters something , for instance you enter 30 50 90 it will return 80 90 , then wiat for another entry and so on.
CODE:
#include <iostream>
#include <string>
#include<vector>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <climits>
using namespace std;
const int length = 17000;
int power(int x){
int sum =2;
for(int i = 0;i<x;i++) {
sum *= 2;
}
return sum;
}
bool ison(int i,int x)
{
if((i>>x) & 1)return true;
return false;
}
int main()
{
while(true){
vector<int> Vec;
int cur = 0;
while (cin >> cur) {
Vec.push_back(cur);
if (cin.get() == '\n') {
break;
}
}
int * sumOfarr1 = new int[length];
int * sumOfarr2 = new int[length];
for(int i = 0; i<length;i++){
sumOfarr1[i] = 0;
}
for(int i = 0; i<length;i++){
sumOfarr2[i] = 0;
}
int index=0;
for(int i=1;i<length;i++)
{
for(int j=0;j<Vec.size();j++)
{
if(ison(i,j))
{
sumOfarr1[index]+=Vec[j];
}
else
{
sumOfarr2[index]+=Vec[j];
}
}index++;
}
int ans=INT_MAX;
int ii;
for(int i=0;i<index;i++)
{
if(abs(sumOfarr1[i]-sumOfarr2[i])<ans)
{
ii=i;
ans=abs(sumOfarr1[i]-sumOfarr2[i]);
}
}
if(sumOfarr1[ii]<sumOfarr2[ii]){
cout << sumOfarr1[ii] << " " << sumOfarr2[ii];
}
else{
cout << sumOfarr2[ii] << " " << sumOfarr1[ii];
}
cout << endl;
delete[] sumOfarr1;
delete[] sumOfarr2;
Vec.clear();
}
return 0;
}
Yes I found the solution just using getline and stringstream.
aka this
vector<int> Vec;
string line;
while(getline( cin, line ))
{
istringstream iss( line );
int number;
while( iss >> number )
Vec.push_back(number);
}
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.
I need to read something like:
5 60 35 42
2 38 6
5 8
300 1500 900
And then save the first line in an array. After calling other functions do the same with the next line, and so on.
I try with gets() and then use sscanf() to scan the integers from the string, but I don't know how to read n numbers from a string.
C++
If you have an unknown number of entries spread across an unknown number of lines, ending at EOF:
int n;
while(cin >> n)
vector_of_int.push_back(n);
If you have a known number of entries spread across an unknown number of lines:
int n;
int number_of_entries = 20; // 20 for example, I don't know how many you have.
for(int i ; i < number_of_entries; ++i)
if(cin >> n)
vector_of_int.push_back(n);
If you have an uknown number of entries on a single line:
std::string str;
std::getline(std::cin, str);
std::istringstream sstr(str);
int n;
while(sstr >> n)
vector_of_int.push_back(n);
If you have a unknown number of entries spread across a known number of lines:
for(int i = 0; i < number_of_lines; ++i) {
std::string str;
if(std::getline(std::cin, str)) {
std::istringstream sstr(str);
int n;
while(sstr >> n)
vector_of_int.push_back(n);
}
}
I've seen input files like this for competitions before. If speed is more of an issue than error detection, you could use a custom routine. Here's one similar to that I use:
void readintline(unsigned int* array, int* size) {
char buffer[101];
size=0;
char* in=buffer;
unsigned int* out=array;
fgets(buffer, 100, stdin);
do {
*out=0;
while(*in>='0') {
*out= *out* 10 + *in-'0';
++in;
}
if (*in)
++in; //skip whitespace
++out;
} while(*in);
size = out-array;
}
It will destroy your memory if there's more than 100 characters on a line, or more numbers than array can hold, but you won't get a faster routine to read in lines of unsigned ints.
On the other hand, if you want simple:
int main() {
std::string tmp;
while(std::getline(std::cin, tmp)) {
std::vector<int> nums;
std::stringstream ss(tmp);
int ti;
while(ss >> ti)
nums.push_back(ti);
//do stuff with nums
}
return 0;
}
I'd probably write the code something like this:
// Warning: untested code.
std::vector<int> read_line_ints(std::istream &is) {
std::string temp;
std::getline(is, temp);
std::istringstream buffer(temp);
int num;
std::vector<int> ret;
while (buffer>>num)
ret.push_back(num);
return ret;
}
In C++, you can use std::istringstream.
std::string nums = "1 20 300 4000";
std::istringstream stream(nums);
int a, b, c, d;
stream >> a >> b >> c >> d;
assert(a == 1 && b == 20 && c == 300 && d == 4000);
If you want to get it from the standard input, then do the same, but just use std::cin
std::cin >> a >> b >> c >> d;
The quick solution is to read them with scanf()
int array[1000];
int index = 0;
while ((index < 1000) && (scanf("%d", &tmp) == 1)) {
array[index++] = tmp;
}
This still needs a bit more validation ...
C++:
vector<int> ints;
while( !cin.eof() )
{
int t;
cin >> t;
if ( !cin.eof() )
ints.push_back(t);
}
Alternative (thx to Shahbaz)
int t;
vector<int> ints;
while(cin >> t)
ints.push_back(t);
In C++ it's extremely simple to read N integers separated by whitespace via stdin:
#include <iostream>
using namespace std;
const unsigned N = 5;
int main(void)
{
int nums[N];
for (unsigned i = 0; i < N; ++i)
cin >> nums[i];
cout << "Your numbers were:\n";
for (unsigned i = 0; i < N; ++i)
cout << nums[i] << " ";
cout << "\n";
return 0;
}