Unable to get output for multiplication - c++

#include<iostream.h>
int main()
{
int n[50],p=0;
double g=1;
char c;
cout<<"\n press a for addition";
cout<<"\n press m for multiplication";
cin>>c;
if(c=='a')
{
for(int i=0;n[i]=!'=',i<50;i++)
{
cin>>n[i];
p+=n[i];
}
cout<<p;
}
else if(c=='m')
{
for(int j=0;n[j]=!'=',j<50;j++)
{
cin>>n[j];
g*=n[j];
}
cout<<g;
}
else cout<<"wrong input";
}
I have wrote this code, it works perfectly fine when addition part is used but when multiplication is done it isn't giving the final product. Whenever I click '=' it doesn't give any final product during multiplication but while addition the same logic works fine.

You have multiple problems:
The array n isn't initialized so its contents will be indeterminate, and using indeterminate values lead to undefined behavior.
Fortunately (for you) the loop "condition" expression n[j]=!'=',j<50 doesn't do what you probably think it does... The part n[j]=!'=' is actually equal to n[j] = !'='. That is you assign the result of !'=' to n[j].
And about the loop "condition", the result of n[j]=!'=',j<50 is the result of j<50 only, because that's how the comma operator works.
With cin>>n[j] you can't read arbitrary characters, as n[j] is an int and you only read int values. The only way to get a '=' from the input is if the user inputs the value 61 which happens to be the ASCII encoded value for '='.
Your loop "condition" also have another flaw, because you increase j before you check n[j], so in the condition n[j] will always be an element of the array that you haven't read into.
And building on the previous point, because the value of j will be wrong in the "condition" you will go out of bounds of the array which also leads to undefined behavior.

Related

why does scanf() turn none into two float

I'm a newbie on c++ and I am encountering some problems. The question to be solved is
having 5 inputs, the inputs can include integers and the string "none", try to sum up the integers in the inputs and the result should be a double.
Here's what I have done: I put five inputs in the array and use scanf() to turn them into double, but when I enter none and use printf to see the array, I found out that it turns none into two float, does scanf has any restrictions on converting strings to double?
Here's the code :
int main()
{
double sc[5];
for (int i = 0; i < 5; i++) {
sc[i] = 3;
scanf("%lf", &sc[i]);
printf("%lf\n", sc[i]);
}
}
and the output is:
34
34.000000
none
3.000000
3.000000
56
56.000000
89
89.000000
Calling scanf("%lf", &something) will populate something if and only if the input is a valid floating point number. The string none is not such a valid number.
The reason you're getting two 3 values is probably because nan is a valid floating point number, so scanf finds the n and says "Hah, this will be a nan". But then it finds, much to its disappointment, the o and decides it's no longer valid.
But it has already read the no from the input stream. It then goes back and does the same thing with the ne (a).
After that, you start giving it valid numbers again so it carries on.
If you want to be able to handle strings and numbers, you're going to have to use the least restrictive (string) and then decide. Something like this (though scanf("%s") is dangerous for real code, it's probably okay for classwork):
The following code does that and (as you should) checks the return value from scanf/sscanf to ensure it was correctly scanned:
#include <stdio.h>
#include <string.h>
int main() {
static char bigstring[1000];
double sc[5];
for (int i = 0; i < 5; i++) {
sc[i] = 3;
if (scanf("%s", bigstring) != 1) {
puts("*** Could not get input");
return 1;
}
if (strcmp("none", bigstring) == 0) {
puts("Got 'none', converting to -999");
sc[i] = -999;
} else if (sscanf(bigstring, "%lf", &sc[i]) != 1) {
printf("*** Could not convert input '%s' to float", bigstring);
return 1;
} else {
printf("Got %f\n", sc[i]);
}
}
puts("\nThe five entered numbers were:");
for (int i = 0; i < 5; i++) {
printf(" %lf\n", sc[i]);
}
}
Running that works properly with basic test data:
pax:~$ printf "34\nnone\n56\n89\n111\n" | ./qq
Got 34.000000
Got 'none', converting to -999
Got 56.000000
Got 89.000000
Got 111.000000
The five entered numbers were:
34.000000
-999.000000
56.000000
89.000000
111.000000
(a) Interestingly, it appears this only happens with real user input, not piping data through the program as per my printf statement.
The ideal behaviour, in my opinion, would be to leave the input stream pointing at the invalid data. In other words, unless the exact text is valid (like nan), the pointer should not move at all. However, there's a footnote in the C standard that allows for this behaviour if, for example, the input stream is not seekable:
fscanf pushes back at most one input character onto the input stream.
So, while it may be able to back up further than that on a pipeline, that may not be the case when dealing with terminal input.
When I enter x as input, it appears it does push that back, because every single following array element is populated with 3, meaning it's reading that x continuously. Anything starting with an n seems to consume that and the following character only.

cout doesn't works properly on my program, can somebody help me?

enter image description hereI am using the STL in c++ and inside a bucle the cout doesn't prints correctly a float.
my program ads values to a vector and then passes it to a function to see if the condition exist, actually it works perfectly but just the cout doesn't word, I already tried using printf() but it gave the same result.
note:please algo give me feedback on my question is the first time i do one and English is not my natal language
my code:
#include<bits/stdc++.h>
#include<vector>
using namespace std;
void isthereanumber(vector<float> array);
int main(){
string ans;vector<float> array;float number;
do{
fflush(stdin);
cout<<"insert a value for the vector: "<<endl;
cin>>number;
array.push_back(number);
fflush(stdin);
cout<<"would you like to keep adding values to the vector? "<<endl;
getline(cin,ans);
}while(ans.compare("yes")==0);
isthereanumber(array);
return 0;
}
void isthereanumber(vector<float> array){
float suma =0;
for(vector<float>::iterator i=array.begin();i!=array.end();i++){
for(vector<float>::iterator j=array.begin();j!=array.end();j++){
if(i!=j){
suma = suma+array[*j];
}
}
if(suma=array[*i]){
cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
return;
}
}
cout<<"there is not a number with such a condition: ";
return;
}
As stated by cleggus already there are some issues present. Those need to be adressed first. After that there's a logical error in that suma just keeps growing.
Given the input 5,5,10 once we test for 10 we would like suma to be set to 0 again for it to work but it will be something like 30 now instead.
That can be solved by moving suma inside the outer loop.
Working example for input 5,5,10: https://godbolt.org/z/gHT6jg
I think you may have a couple of issues...
In your for loops you are creating iterators to the vector, but rather than just dereferencing them to access the indexed element you are dereferencing them and then using that as an index to the same vector.
Also Your last if statement has an assignment = rather than a comparison ==.
I believe this is closer to what you are trying to achieve (sorry I haven't had time to compile and check):
for(vector<float>::iterator i=array.begin();i!=array.end();i++){
for(vector<float>::iterator j=array.begin();j!=array.end();j++){
if(i!=j){
suma = suma+*j;
}
}
if(suma==*i){
cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
return;
}
}

converting string vectors to int

I have to make a program that reads information for a student from a file, and I made a couple of vectors to keep all that information. But then I need to sum up the absences of all the students, so I need to convert them to integer, however when I try to the program runs, but crashes immediately when it reaches the atoi part.
while(!read.eof()) {
if(i==4){
i=0;
}
read>>b;
if(i==0){ names.push_back(b); }
if(i==1){ last_name.push_back(b); }
if(i==2){ absences.push_back(b); }
if(i==3){ unatoned.push_back(b); }
i++;
}
int a = atoi(absences[0].c_str());
If absences remains empty then the behaviour of absences[0] is undefined.
Using absences.at(0) when absences is empty forces the compiler to throw an exception so is easier to work with.
Either way, for the number of absences, use simply
auto a = absences.size();
You should change you absences vector to be a vector of int:
std::vector<int> abscences;
// rest of the code...
The read >> var instruction will take care of the conversion.
Of course, the >> operator will not write into the integer if it's invalid.

Addition of array elements: lvalue required as left operand of assignment

I've been trying for a while to do a specific problem that our teacher gave us at school if we wanted to earn a good grade but I couldn't do it.
But now, I'm actually very interested in solving this.
{
int i,n,a[100],c;
cout <<"n=";
cin >>n;
for(i=1;i<=n;i++)
{
cout <<"a["<<i<<"]=";
cin>> a[i];
}
for (i=2;i<=n-1;i++)
if (a[i]/10==0)
{
c=a[i];
a[i]=a[i-1]+a[i+1];
a[i-1]+a[i+1]=c;
}
for (i=1;i<=n;i++)
{
cout<<"a["<<i<<"]="<<a[i]<<endl;
}
return 0;
}
ERROR AT: a[i-1]+a[i+1]=c;
lvalue required as left operand of assignment.
The questions I have to solve with this once it's done are, for example: What will be shown for n=5 and the vector a=(22,4,10,5,16)?
Hi, Richard. I actually don't want anything to happen on that line but the reason for why that error occurs. What I'm doing with that part of the code is to apply the interchange algorithm, so that, for example, when the code is finished and I'll have to press F9 in the CodeBlocks Application, there will be a chosen n, which the problem tells me that it's 5, and then I'll have to pick the 5 numbers shown in the a vector which are 22,4,10,5,16
ex: a[1]=22, a[2]=4, a[3]=10, a[4]=5, a[5]=16.. When all of that is done, the application has to change my a[1] with a[2], so a[1] will have the value of a[2] and so on.
You are assigning a value to a constant: a[i-1]+a[i+1]=c;
Because the statement above doesn't return an address of the element but the value in that address which is of course constant. It is like you write:
5 = n;
To solve your problem then:
(a[i-1]+a[i+1])=c; becomes:
c = (a[i-1]+a[i+1]); // because c is not a constant

ARRAYS DEBUGGING incorrect outputs, complex algorithm

I made this algorithm, i was debugging it to see why it wasnt working, but then i started getting weird stuff while printing arrays at the end of each cycle to see where the problem first occurred.
At a first glance, it seemed my while cycles didn't take into consideration the last array value, but i dunno...
all info about algorithm and everything is in the source.
What i'd like to understand is, primarily, the answer to this question:
Why does the output change sometimes?? If i run the program, 60-70% of the time i get answer 14 (which should be wrong), but some other times i get weird stuff as the result...why??
how can i debug the code if i keep getting different results....plus, if i compile for release and not debug (running codeblocks under latest gcc available in debian sid here), i get most of the times 9 as result.
CODE:
#include <iostream>
#include <vector>
/*void print_array
{
std::cout<<" ( ";
for (int i = 0; i < n; i++) { std::cout<<array[i]<<" "; }
std::cout<<")"<<std::endl;
}*/
///this algorithm must take an array of elements and return the maximum achievable sum
///within any of the sub-arrays (or sub-segments) of the array (the sum must be composed of adjacent numbers within the array)
///it will squeeze the array ...(...positive numbers...)(...negative numbers...)(...positive numbers...)...
///into ...(positive number)(negative number)(positive number)...
///then it will 'remove' any negative numbers in case it would be convienent so that the sum between 2 positive numbers
///separated by 1 negative number would result in the highest achievable number, like this:
// -- (3,-4,4) if u do 'remove' the negative number in order to unite the positive ones, i will get 3-4+4=3. So it would
// be better not to remove the negative number, and let 4 be the highest number achievable, without any sums
// -- (3,-1,4) in this case removing -1 will result in 3-1+4=6, 6 is bigger than both 3 and 4, so it would be convienent to remove the
// negative number and sum all of the three up into one number
///so what this step does is shrink the array furthermore if it is possible to 'remove' any negatives in a smart way
///i also make it reiterate for as long as there is no more shrinking available, because if you think about it not always
///can the pc know if, after a shrinking has occured, there are more shrinkings to be done
///then, lastly, it will calculate which of the positive numbers left is highest, and it will choose that as remaining maximum sum :)
///expected result for the array of input, s[], would be (i think), 7
int main() {
const int n=4;
int s[n+1]={3,-2,4,-4,6};
int k[n+1]={0};
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
int i=0, j=0;
// step 1: compress negative and postive subsegments of array s[] into single numbers within array k[]
/*while (i<=n)
{
while (s[i]>=0)
{
k[j]+=s[i]; ++i;
}
++j;
while (s[i]<0)
{
k[j]+=s[i]; ++i;
}
++j;
}*/
while (i<=n)
{
while (s[i]>=0)
{
if (i>n) break;
k[j]+=s[i]; ++i;
}
++j;
while (s[i]<0)
{
if (i>n) break;
k[j]+=s[i]; ++i;
}
++j;
}
std::cout<<"STEP 1 : ";
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
j=0;
// step 2: remove negative numbers when handy
std::cout<<"checked WRONG! "<<unsigned(k[3])<<std::endl;
int p=1;
while (p!=0)
{
p=0;
while (j<=n)
{
std::cout<<"checked right! "<<unsigned(k[j+1])<<std::endl;
if (k[j]<=0) { ++j; continue;}
if ( k[j]>unsigned(k[j+1]) && k[j+2]>unsigned(k[j+1]) )
{
std::cout<<"checked right!"<<std::endl;
k[j+2]=k[j]+k[j+1]+k[j+2];
k[j]=0; k[j+1]=0;
++p;
}
j+=2;
}
}
std::cout<<"STEP 2 : ";
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
j=0; i=0; //i will now use "i" and "p" variables for completely different purposes, as not to waste memory
// i will be final value that algorithm needed to find
// p will be a value to put within i if it is the biggest number found yet, it will keep changing as i go through the array....
// step 3: check which positive number is bigger: IT IS THE MAX ACHIEVABLE SUM!!
while (j<=n)
{
if(k[j]<=0) { ++j; continue; }
p=k[j]; if (p>i) { std::swap(p,i); }
j+=2;
}
std::cout<<std::endl<<"MAX ACHIEVABLE SUM WITHIN SUBSEGMENTS OF ARRAY : "<<i<<std::endl;
return 0;
}
might there be problems because im not using vectors??
Thanks for your help!
EDIT: i found both my algorithm bugs!
one is the one mentioned by user m24p, found in step 1 of the algorithm, which i fixed with a kinda-ugly get-around which ill get to cleaning up later...
the other is found in step2. it seems that in the while expression check, where i check something against unsigned values of the array, what is really checked is that something agains unsigned values of some weird numbers.
i tested it, with simple cout output:
IF i do unsigned(k[anyindexofk]) and the value contained in that spot is a positive number, i get the positive number of course which is unsigned
IF that number is negative though, the value won't be simply unsigned, but look very different, like i stepped over the array or something...i get this number "4294967292" when im instead expecting -2 to return as 2 or -4 to be 4.
(that number is for -4, -2 gives 4294967294)
I edited the sources with my new stuff, thanks for the help!
EDIT 2: nvm i resolved with std::abs() using cmath libs of c++
would there have been any other ways without using abs?
In your code, you have:
while (s[i]>=0)
{
k[j]+=s[i]; ++i;
}
Where s is initialized like so
int s[n+1]={3,-2,4,-4,6};
This is one obvious bug. Your while loop will overstep the array and hit garbage data that may or may not be zeroed out. Nothing stops i from being bigger than n+1. Clean up your code so that you don't overstep arrays, and then try debugging it. Also, your question is needs to be much more specific for me to feel comfortable answering your question, but fixing bugs like the one I pointed out should make it easier to stop running into inconsistent, undefined behavior and start focusing on your algorithm. I would love to answer the question but I just can't parse what you're specifically asking or what's going wrong.