I have to create a gradebook that reads in any amount of students and what their grades are. The user can add more to the matrix if they need another column of grades. I am having a problem with my addGrades function and need help on what is worng and how I can fix it. Here is the function for my "Add Grades" function:
void AddGrades(vector%26lt;String%26gt; %26amp;name, TTTBoard %26amp;Board)
{
int Row = Board.numrows() - 1;
int Col = Board.numcols() - 1;
//Board.resize(Col,Row);
//for(int j=0;j%26lt;= Col;j++){
for(int i = 0; i %26lt; Row; i++){
cout%26lt;%26lt;"Please enter a grade for "%26lt;%26lt;name[i]%26lt;%26lt;" ";
cin%26gt;%26gt;Board[Row][i]; //j,i ?
Row++;
}//end for
//}//end for
}//end fun.
//Thanks.
C++ maxtrix?
void AddGrades(vector%26lt;String%26gt; %26amp;name, TTTBoard %26amp;Board)
{
int Row = Board.numrows() - 1;
for(int i = 0; i %26lt; Row; i++){
cout%26lt;%26lt;"Please enter a grade for "%26lt;%26lt;Name[i]%26lt;%26lt;" ";
cin%26gt;%26gt;Board[i];
}//end for
}//end fun.
Reply:This if for a console app fight? Hence the cout statements? If so, the cin statement only needs to be seperated by commas.... and why are you using { instead of ; for the endings of a few of your lines of code?
floral design
Monday, May 24, 2010
Saving the enter key in array..c++??
cin.get cant do that nor can cin%26gt;%26gt;
so how do i do it??
Saving the enter key in array..c++??
cin%26gt;%26gt;"here witte the arry as you predifine"
this can save your arry.
so how do i do it??
Saving the enter key in array..c++??
cin%26gt;%26gt;"here witte the arry as you predifine"
this can save your arry.
C++ heap problem (new fuction)?
How do I create an array of Employees at run time? The size of the array is entered by the user.
I tried...
cin %26gt;%26gt; num;
Employee[] emp = new Employee[num];
but its wrong.
C++ heap problem (new fuction)?
Does it need to be an array? Why don't you use a vector?
this is what vectors are used for.
Reply:This should work fine:
Employee* pemp = new Employee[num];
Then pemp[0] to get the first element, pemp[1], etc.
Ensure you never read past pemp[num-1] as that is not your memory.
Reply:1. use a array of character pointers (string)
2. then create a buffer say buffer[255] that will accept user input
3. get the length of the string entered
4. then use malloc to allocate storage for the string
5. copy the entered string to the storage allocated in 4
6. do steps 4 to 5 for every new employee
Reply:You need to initialize your Employee (class) to zero (0) before you create the array. I believe this is called the "default constructor". Also, when you the function has run its course, you must destroy the array with: delete Employee; . Otherwise, the memory (heap) manager will cause a run time error. Remember, C++ does not have automatic garbage collection, though Java does.
I tried...
cin %26gt;%26gt; num;
Employee[] emp = new Employee[num];
but its wrong.
C++ heap problem (new fuction)?
Does it need to be an array? Why don't you use a vector?
this is what vectors are used for.
Reply:This should work fine:
Employee* pemp = new Employee[num];
Then pemp[0] to get the first element, pemp[1], etc.
Ensure you never read past pemp[num-1] as that is not your memory.
Reply:1. use a array of character pointers (string)
2. then create a buffer say buffer[255] that will accept user input
3. get the length of the string entered
4. then use malloc to allocate storage for the string
5. copy the entered string to the storage allocated in 4
6. do steps 4 to 5 for every new employee
Reply:You need to initialize your Employee (class) to zero (0) before you create the array. I believe this is called the "default constructor". Also, when you the function has run its course, you must destroy the array with: delete Employee; . Otherwise, the memory (heap) manager will cause a run time error. Remember, C++ does not have automatic garbage collection, though Java does.
C++ Strings?
I have to take in a a string and scramble it 5 times, using string methods. I have to separate it using 2 radnom num's, and into three parts. It won't execute for some reason. Any help will be appreciated. Here's the code:
cout%26lt;%26lt;endl;
cout%26lt;%26lt;"Enter a phrase to shuffle: ";
getline(cin,phrase_input);
for(int i = 0;i %26lt;= 5;i++)
{
beg = phrase_new.substr(0,random_one);
mid = phrase_new.substr(random_one,random_two - random_one);
endphr = phrase_new.substr(random_two,phr_len - random_two);
shuffled_phrased+= endphr;
shuffled_phrased+= beg;
shuffled_phrased+= mid;
}
cout%26lt;%26lt;shuffled_phrased;
C++ Strings?
first, I assume that somewhere you are copying phrase_input into phrase_new somewhere and just didnt show the code.
second, make sure your random_one and random_two are not greater than the length of the string phrase_new.
third, to loop 5 times, your "for" loop should be "for(int i = 0; i %26lt; 5; i++)"
fourth, you need to copy shuffled_phrased back into phrase_new at the end of your loop, so you can repeat the operations on it again.
Reply:Do you know how to use a debugger?
If not, I suggest you learn.
A debugger will help you to pinpoint a problem to a specific line of code. Learn to step through the code and verify it is doing what it is supposed to be doing.
Learn to use breakpoints and the call stack.
cout%26lt;%26lt;endl;
cout%26lt;%26lt;"Enter a phrase to shuffle: ";
getline(cin,phrase_input);
for(int i = 0;i %26lt;= 5;i++)
{
beg = phrase_new.substr(0,random_one);
mid = phrase_new.substr(random_one,random_two - random_one);
endphr = phrase_new.substr(random_two,phr_len - random_two);
shuffled_phrased+= endphr;
shuffled_phrased+= beg;
shuffled_phrased+= mid;
}
cout%26lt;%26lt;shuffled_phrased;
C++ Strings?
first, I assume that somewhere you are copying phrase_input into phrase_new somewhere and just didnt show the code.
second, make sure your random_one and random_two are not greater than the length of the string phrase_new.
third, to loop 5 times, your "for" loop should be "for(int i = 0; i %26lt; 5; i++)"
fourth, you need to copy shuffled_phrased back into phrase_new at the end of your loop, so you can repeat the operations on it again.
Reply:Do you know how to use a debugger?
If not, I suggest you learn.
A debugger will help you to pinpoint a problem to a specific line of code. Learn to step through the code and verify it is doing what it is supposed to be doing.
Learn to use breakpoints and the call stack.
C++ Vectors?
The instructions for this problem are:
" Write a complete program that reads in 100 double values from standard input (keyboard) into a vector. Then output all 100 values to standard output (terminal) in the same order they were read in with one space between each value."
I do not need to worry about prompting the user with instructions.
The code I have so far is:
#include %26lt;iostream%26gt;
#include %26lt;vector%26gt;
int main()
{
vector%26lt;double%26gt; values(99);
while( int i = 0 ; i %26lt;= 99 ; i++ )
{
cin %26lt;%26lt; vector[i];
}
for ( int i = 1 ; i %26lt; values.size()-1 ; i++ )
{
cout %26lt;%26lt; vector[i] %26lt;%26lt; " " ;
}
return 0;
}
Could someone please tell me what I am doing wrong? Thanks in advance.
C++ Vectors?
Here is correct code based on your code:
#include %26lt;iostream%26gt;
#include %26lt;vector%26gt;
using namespace std;
const static int vec_sz = 100;
vector%26lt;double%26gt; values(vec_sz);
int main( int ac, char * av[] )
{
for( int i = 0 ; i %26lt; vec_sz ; i++ )
{
cin %26gt;%26gt; values[i];
}
for ( int i = 0 ; i %26lt; vec_sz ; i++ )
{
cout %26lt;%26lt; values[i] %26lt;%26lt; " " ;
}
return 0;
}
Reply:cin %26gt;%26gt; values[i]; (not %26lt;%26lt;)
and cout %26lt;%26lt; values[i], not vector[i]
if the cin doesn't work (vector::operator[] returns a reference so it should in theory) use a temporary double variable first then assign that into the vector.
chelsea flower show
" Write a complete program that reads in 100 double values from standard input (keyboard) into a vector. Then output all 100 values to standard output (terminal) in the same order they were read in with one space between each value."
I do not need to worry about prompting the user with instructions.
The code I have so far is:
#include %26lt;iostream%26gt;
#include %26lt;vector%26gt;
int main()
{
vector%26lt;double%26gt; values(99);
while( int i = 0 ; i %26lt;= 99 ; i++ )
{
cin %26lt;%26lt; vector[i];
}
for ( int i = 1 ; i %26lt; values.size()-1 ; i++ )
{
cout %26lt;%26lt; vector[i] %26lt;%26lt; " " ;
}
return 0;
}
Could someone please tell me what I am doing wrong? Thanks in advance.
C++ Vectors?
Here is correct code based on your code:
#include %26lt;iostream%26gt;
#include %26lt;vector%26gt;
using namespace std;
const static int vec_sz = 100;
vector%26lt;double%26gt; values(vec_sz);
int main( int ac, char * av[] )
{
for( int i = 0 ; i %26lt; vec_sz ; i++ )
{
cin %26gt;%26gt; values[i];
}
for ( int i = 0 ; i %26lt; vec_sz ; i++ )
{
cout %26lt;%26lt; values[i] %26lt;%26lt; " " ;
}
return 0;
}
Reply:cin %26gt;%26gt; values[i]; (not %26lt;%26lt;)
and cout %26lt;%26lt; values[i], not vector[i]
if the cin doesn't work (vector::operator[] returns a reference so it should in theory) use a temporary double variable first then assign that into the vector.
chelsea flower show
Can someone please tell me what's wrong with my C++ program?this program should show how many students earned
a specific score. it is not working because i type inn 72 and it shows 20. the array only has two 72 scores. then, if i want to type inn another score, i have to type it twice in order for the screen to show an output. this is my code:
#include %26lt;iostream%26gt;
using std::cout;
using std::cin;
using std::endl;
int main()
{
//declare array
int count = 0;
int searchFor = 0;
int scores[20] = {90, 54, 23, 75, 67, 89, 99, 100, 34, 99,
97, 76, 73, 72, 56, 73, 72, 20, 86, 99};
//get input from user
while (searchFor != -1)
{
cout %26lt;%26lt; "Enter a score from 0 to 100: " ;
cin %26gt;%26gt; searchFor;
//search for score equal to the searchFor value
for (int x = 0; x %26lt; 20; x = x + 1)
if (scores[x] = searchFor)
count = count + 1;
//end if
//end for
//display cout
cout %26lt;%26lt; "Count: " %26lt;%26lt; count %26lt;%26lt;endl;
//get input from user
cout %26lt;%26lt; "Enter a score from 0 to 100: " ;
cin %26gt;%26gt; searchFor;
}//endwhile
return 0;
} //end of the searchArray function
Can someone please tell me what's wrong with my C++ program?this program should show how many students earned
There has to be == on the if statement
while (searchFor != -1)
{
// User enters a score
cout %26lt;%26lt; "Enter a score from 0 to 100: " ;
cin %26gt;%26gt; searchFor;
// If score is in the array, then add to count
for (int x = 0; x %26lt; 20; x++)
{
if (scores[x] == searchFor)
count++;
}
// Display count
cout %26lt;%26lt; "Count: " %26lt;%26lt; count %26lt;%26lt;endl;
}
return 0;
}//end of the searchArray function
#include %26lt;iostream%26gt;
using std::cout;
using std::cin;
using std::endl;
int main()
{
//declare array
int count = 0;
int searchFor = 0;
int scores[20] = {90, 54, 23, 75, 67, 89, 99, 100, 34, 99,
97, 76, 73, 72, 56, 73, 72, 20, 86, 99};
//get input from user
while (searchFor != -1)
{
cout %26lt;%26lt; "Enter a score from 0 to 100: " ;
cin %26gt;%26gt; searchFor;
//search for score equal to the searchFor value
for (int x = 0; x %26lt; 20; x = x + 1)
if (scores[x] = searchFor)
count = count + 1;
//end if
//end for
//display cout
cout %26lt;%26lt; "Count: " %26lt;%26lt; count %26lt;%26lt;endl;
//get input from user
cout %26lt;%26lt; "Enter a score from 0 to 100: " ;
cin %26gt;%26gt; searchFor;
}//endwhile
return 0;
} //end of the searchArray function
Can someone please tell me what's wrong with my C++ program?this program should show how many students earned
There has to be == on the if statement
while (searchFor != -1)
{
// User enters a score
cout %26lt;%26lt; "Enter a score from 0 to 100: " ;
cin %26gt;%26gt; searchFor;
// If score is in the array, then add to count
for (int x = 0; x %26lt; 20; x++)
{
if (scores[x] == searchFor)
count++;
}
// Display count
cout %26lt;%26lt; "Count: " %26lt;%26lt; count %26lt;%26lt;endl;
}
return 0;
}//end of the searchArray function
How do I get rid of the newline character in C++ using ignore?
I have this class structure, I'm trying to read in strings.
for (int count = 0; count %26lt; num; count++) {
cfile %26gt;%26gt; library[count].name.last;
cfile %26gt;%26gt; library[count].name.first;
getline(cfile, library[count].book.title);
cfile %26gt;%26gt; library[count].book.pages;
getline(cfile, library[count].book.genre);
getline(cfile, library[count].book.other.publisher);
cfile %26gt;%26gt; library[count].book.other.year;
}
And I asked this guy and he said:
After you cin%26gt;%26gt; name.first and name.last, you will have read "Jk" and "Rowling", respectively, but you've left the newline in the stream. The call to getline will receive an empty line, and when you try to convert that empty string to a number, you get something completely random like 211400.
How do I get rid of the newline character, something to do with cin.ignore????
How do I get rid of the newline character in C++ using ignore?
The guy you asked answered correctly. When reading from an instream object using %26gt;%26gt;, you have to be careful about newlines being left behind.
I could type up the solution here, but someone else has already done so. I'll give you the link: http://www.daniweb.com/tutorials/tutoria...
I'll summarize the two solutions you have. The first, and recommended for beginners to C++, is to avoid cin and use getline instead. The other way is cin.ignore(numeric_limits%26lt;streamsize%26gt;::m... '\n').
Please read the entire article. It is technically accurate as well.
In the future, use Google to find out answers. There's good resources at "C++ FAQ", cplusplus.com , cppreference.com.
Reply:cin.ignore('\n');
for (int count = 0; count %26lt; num; count++) {
cfile %26gt;%26gt; library[count].name.last;
cfile %26gt;%26gt; library[count].name.first;
getline(cfile, library[count].book.title);
cfile %26gt;%26gt; library[count].book.pages;
getline(cfile, library[count].book.genre);
getline(cfile, library[count].book.other.publisher);
cfile %26gt;%26gt; library[count].book.other.year;
}
And I asked this guy and he said:
After you cin%26gt;%26gt; name.first and name.last, you will have read "Jk" and "Rowling", respectively, but you've left the newline in the stream. The call to getline will receive an empty line, and when you try to convert that empty string to a number, you get something completely random like 211400.
How do I get rid of the newline character, something to do with cin.ignore????
How do I get rid of the newline character in C++ using ignore?
The guy you asked answered correctly. When reading from an instream object using %26gt;%26gt;, you have to be careful about newlines being left behind.
I could type up the solution here, but someone else has already done so. I'll give you the link: http://www.daniweb.com/tutorials/tutoria...
I'll summarize the two solutions you have. The first, and recommended for beginners to C++, is to avoid cin and use getline instead. The other way is cin.ignore(numeric_limits%26lt;streamsize%26gt;::m... '\n').
Please read the entire article. It is technically accurate as well.
In the future, use Google to find out answers. There's good resources at "C++ FAQ", cplusplus.com , cppreference.com.
Reply:cin.ignore('\n');
Is there an efficient way to toss binary data in C++?
Below if the code I'm using. I wonder if anyone knows a faster way to do what I'm doing, which is taking in a file by reading its data byte by byte, and throwing out every other byte (so the final output is 1/2 the original).
I find that that way I'm doing it is really slow. Is there a way to do this faster? I think that reading the file in at once might speed things up so that cin doesn't have to be called over and over, but I don't know how to go about doing that.
#include%26lt;iostream%26gt;
using namespace std;
main()
{int i=0;
char ch;
while(cin.get(ch))
{if(i == 1)
{cout %26lt;%26lt; ch;
i = 0;
}
else if(i == 0)
{i = 1;
}
else {exit(-1);}
}
}
Is there an efficient way to toss binary data in C++?
You'd be better off reading the entire file into a dynamically allocated array to begin with, then using pointer arithmetic to remove the unnecessary bytes. File accesses are super slow, but if you read the entire thing first you can do it by reading in much bigger chunks and then just iterate over the list of read in data and skip every other byte.
I find that that way I'm doing it is really slow. Is there a way to do this faster? I think that reading the file in at once might speed things up so that cin doesn't have to be called over and over, but I don't know how to go about doing that.
#include%26lt;iostream%26gt;
using namespace std;
main()
{int i=0;
char ch;
while(cin.get(ch))
{if(i == 1)
{cout %26lt;%26lt; ch;
i = 0;
}
else if(i == 0)
{i = 1;
}
else {exit(-1);}
}
}
Is there an efficient way to toss binary data in C++?
You'd be better off reading the entire file into a dynamically allocated array to begin with, then using pointer arithmetic to remove the unnecessary bytes. File accesses are super slow, but if you read the entire thing first you can do it by reading in much bigger chunks and then just iterate over the list of read in data and skip every other byte.
Validating crap in c++?
i'm trying to validate numbers as I enter them in my program. can anyone tell me whats wrong with this?
cout %26lt;%26lt; "\nHow many whole numbers (up to 20) would you like to organize? ";
cin %26gt;%26gt; numberNum;
if (numberNum != '0','1','2','3','4','5','6','7','8','9' )
{
cout %26lt;%26lt; "Please enter a valid number: " %26lt;%26lt; endl;
}
everytime i run the program, the message pops up. its as if the compiler sees the valids "1,2,3..." as invalid. any suggestions?
Validating crap in c++?
why don't u try this
cout %26lt;%26lt; "\nHow many whole numbers (up to 20) would you like to organize? ";
cin %26gt;%26gt; numberNum;
if (numberNum %26gt; 20 || numberNum %26lt;0)
{
cout %26lt;%26lt; "Please enter a valid number: " %26lt;%26lt; endl;
cin %26gt;%26gt; numberNum
}
Reply:The comma is a valid C++ operator, but it doesn't do what you're thinking it does. The comma evaluates the expression on its left, discarding the result, then returns the type and value of the expression on the right. Also, you're making your life difficult. For 0-20, it's difficult, but what if you wanted the numbers 0-100 to be valid?! Typing them all out would get insane, and a phone number, a MILLION possible numbers you don't want to type!
use if(numberNum %26gt;= 0 %26amp;%26amp; numbernNum%26lt;=20)
now if you want to expand it to a million all you have to change it to would be
if(numberNum %26gt;= 0 %26amp;%26amp; numberNum%26lt;= 10000000)
(you'd also have to make it an integer, but a search of answers will tell you how to do that).
Reply:instead you need this...
if (numberNum != '0' %26amp;%26amp; numberNum != '1' %26amp;%26amp; numberNum != '2') //etc
Perhaps a better way to ensure the validity of the input is to get it as a string using getline, then pass it to a function like atoi() and check for an error.
Reply:This only checks 0. You need :
if ((numberNum %26gt;-1) %26amp;%26amp; (numberNum %26lt;20)
{//routine for a match
}else
{//routine for no match
}
Reply:"numberNum != '0','1','2','3','4','5','6','7'..." is not valid.
You would need to do this: "numberNum != '0' %26amp;%26amp; numberNum != '1' %26amp;%26amp; numberNum != '2'..."
Otherwise, instead of using cin, do this:
int numberNum;
scanf(%d , %26amp;numberNum ); //read in the value as an integer
if( numberNum %26lt; 0 || numberNum %26gt; 20) {
....
}
apple
cout %26lt;%26lt; "\nHow many whole numbers (up to 20) would you like to organize? ";
cin %26gt;%26gt; numberNum;
if (numberNum != '0','1','2','3','4','5','6','7','8','9' )
{
cout %26lt;%26lt; "Please enter a valid number: " %26lt;%26lt; endl;
}
everytime i run the program, the message pops up. its as if the compiler sees the valids "1,2,3..." as invalid. any suggestions?
Validating crap in c++?
why don't u try this
cout %26lt;%26lt; "\nHow many whole numbers (up to 20) would you like to organize? ";
cin %26gt;%26gt; numberNum;
if (numberNum %26gt; 20 || numberNum %26lt;0)
{
cout %26lt;%26lt; "Please enter a valid number: " %26lt;%26lt; endl;
cin %26gt;%26gt; numberNum
}
Reply:The comma is a valid C++ operator, but it doesn't do what you're thinking it does. The comma evaluates the expression on its left, discarding the result, then returns the type and value of the expression on the right. Also, you're making your life difficult. For 0-20, it's difficult, but what if you wanted the numbers 0-100 to be valid?! Typing them all out would get insane, and a phone number, a MILLION possible numbers you don't want to type!
use if(numberNum %26gt;= 0 %26amp;%26amp; numbernNum%26lt;=20)
now if you want to expand it to a million all you have to change it to would be
if(numberNum %26gt;= 0 %26amp;%26amp; numberNum%26lt;= 10000000)
(you'd also have to make it an integer, but a search of answers will tell you how to do that).
Reply:instead you need this...
if (numberNum != '0' %26amp;%26amp; numberNum != '1' %26amp;%26amp; numberNum != '2') //etc
Perhaps a better way to ensure the validity of the input is to get it as a string using getline, then pass it to a function like atoi() and check for an error.
Reply:This only checks 0. You need :
if ((numberNum %26gt;-1) %26amp;%26amp; (numberNum %26lt;20)
{//routine for a match
}else
{//routine for no match
}
Reply:"numberNum != '0','1','2','3','4','5','6','7'..." is not valid.
You would need to do this: "numberNum != '0' %26amp;%26amp; numberNum != '1' %26amp;%26amp; numberNum != '2'..."
Otherwise, instead of using cin, do this:
int numberNum;
scanf(%d , %26amp;numberNum ); //read in the value as an integer
if( numberNum %26lt; 0 || numberNum %26gt; 20) {
....
}
apple
Why doesnt my C++ program work? Help!?
ok so im supposed to write a program that calculates n! using functinos, this is what i have so far.
#include %26lt;iostream%26gt;
using namespace std;
int fact(int n, Int factor, int i)
{
for (int i=1;i%26lt;=n;i++)
factor = factor * i;
return factor;
}
int main ()
{
int n, factor, i;
cout%26lt;%26lt;"Enter a number"%26lt;%26lt;"\n";
cin%26gt;%26gt;n;
factor = fact(n,factor,i);
cout%26lt;%26lt;factor;
return 0;
}
i copile it and it checks out but my answer is always zero. Can anyone see what i did wrong?
Why doesnt my C++ program work? Help!?
%26gt; i did but all i got then was an error message, NO feaken
%26gt; WAY!!!! I did before and all i got was an error message
%26gt; i did it just now again and it worked, wtf!!! My comp is
%26gt; messing with me, (Argg)
Welcome to the world of programming! It sucks! You're gonna love it...
Reply:try initializing factor to 1 before calling the function.
Reply:Change the line 'int n,factor,i;' to this:
int n,i;
unsigned long factor=1;
In your original program, 'factor' was not initialized, so the initial value could have been anything. Also, by using an unsigned long data type for 'factor', the program will allow a number up to 4294967295.
You had 'factor' as an integer, so the maximum number it can hold is 32767.
Reply:hey man what are you doing its all wrong let me write that for you. It goes like this........
# include%26lt;iostream.h%26gt;
int fact(int n)
{ int factorial=1;
for (int i=1;i%26lt;=n;i++)
{
factorial=factorial*i;
}
return factorial;
}
int main()
{
int n;
cin%26gt;%26gt;n;
int factorial=fact(n);
cout%26lt;%26lt;factorial;
return 0
}
hope it helps.
#include %26lt;iostream%26gt;
using namespace std;
int fact(int n, Int factor, int i)
{
for (int i=1;i%26lt;=n;i++)
factor = factor * i;
return factor;
}
int main ()
{
int n, factor, i;
cout%26lt;%26lt;"Enter a number"%26lt;%26lt;"\n";
cin%26gt;%26gt;n;
factor = fact(n,factor,i);
cout%26lt;%26lt;factor;
return 0;
}
i copile it and it checks out but my answer is always zero. Can anyone see what i did wrong?
Why doesnt my C++ program work? Help!?
%26gt; i did but all i got then was an error message, NO feaken
%26gt; WAY!!!! I did before and all i got was an error message
%26gt; i did it just now again and it worked, wtf!!! My comp is
%26gt; messing with me, (Argg)
Welcome to the world of programming! It sucks! You're gonna love it...
Reply:try initializing factor to 1 before calling the function.
Reply:Change the line 'int n,factor,i;' to this:
int n,i;
unsigned long factor=1;
In your original program, 'factor' was not initialized, so the initial value could have been anything. Also, by using an unsigned long data type for 'factor', the program will allow a number up to 4294967295.
You had 'factor' as an integer, so the maximum number it can hold is 32767.
Reply:hey man what are you doing its all wrong let me write that for you. It goes like this........
# include%26lt;iostream.h%26gt;
int fact(int n)
{ int factorial=1;
for (int i=1;i%26lt;=n;i++)
{
factorial=factorial*i;
}
return factorial;
}
int main()
{
int n;
cin%26gt;%26gt;n;
int factorial=fact(n);
cout%26lt;%26lt;factorial;
return 0
}
hope it helps.
Cannot get this C++ program to compile using bounds.. help plz!?
Okay, this program consists of repeated calls to 2 functions to compute the sum and product of all integers between two bounds. For my example, the user is imputing 3 for lower bound, and 7 for upper bound.
I cannot get this program to compile, and suggestions would be great! I will need to add a count controlled loop to this program later, I will just have to try to figure that out once i can get this portion to work though.
My code so far:
#include %26lt;iostream%26gt;
using namespace std;
int main();
int sum(int lower, int upper){
cout %26lt;%26lt; " Enter a lower and upper bound: ";
cin %26gt;%26gt; lower %26gt;%26gt; upper;
int total = 0; //holds the total that will be returned
for(int i = lower; i %26lt;= upper; i++); //calculate the total
total += i; //returns the total, which is the sum 25 (3 + 4 + 5 + 6 + 7)
return total;
}
Thanks in advance!!
Cannot get this C++ program to compile using bounds.. help plz!?
First you ask for product and now you are asking about sum,. It would be better if you do it yourself
Reply:this should work
#include %26lt;iostream%26gt;
using namespace std;
int getNums(int %26amp;lower, int %26amp;upper);
int sum(int, int);
int main(){
int upper=0, lower=0, total=0;
getNums(lower, upper);
total = sum(upper, lower);
return 0;
}
int sum(int upper, int lower){
int total=0;
for(int i=lower; i%26lt;=upper; i++)
i+=total;
return total;
}
int sum(int %26amp;lower, int %26amp;upper){
cout %26lt;%26lt; "Type a lower and upper bounds:\n";
cin %26gt;%26gt; lower;
cin %26gt;%26gt; upper;
return 0;
}
Reply:In C++, to get this to compile you have a bad arrangement of braces that must be remedied. I'll show them in a better light below.
#include %26lt;iostream%26gt;
using namespace std;
int sum(void){//definition of function. { required.
int lower, upper;
cout %26lt;%26lt; " Enter a lower and upper bound: ";
cin %26gt;%26gt; lower %26gt;%26gt; upper;
int total = 0; //holds the total that will be //returned
for(int i = lower; i %26lt;= upper; i++){ //calculate the //total
total += i; //returns the total, which is the sum //25 (3 + 4 + 5 + 6 + 7)
}//end of for loop.
return total;
} // end of function sum.
int main(){
cout %26lt;%26lt; sum();
return 0;
}// end of main.
I've got it so it will compile, so start in from there and reread any material you've got on what demarcates a function in C/C++. I hope this helps. Pivy.
I cannot get this program to compile, and suggestions would be great! I will need to add a count controlled loop to this program later, I will just have to try to figure that out once i can get this portion to work though.
My code so far:
#include %26lt;iostream%26gt;
using namespace std;
int main();
int sum(int lower, int upper){
cout %26lt;%26lt; " Enter a lower and upper bound: ";
cin %26gt;%26gt; lower %26gt;%26gt; upper;
int total = 0; //holds the total that will be returned
for(int i = lower; i %26lt;= upper; i++); //calculate the total
total += i; //returns the total, which is the sum 25 (3 + 4 + 5 + 6 + 7)
return total;
}
Thanks in advance!!
Cannot get this C++ program to compile using bounds.. help plz!?
First you ask for product and now you are asking about sum,. It would be better if you do it yourself
Reply:this should work
#include %26lt;iostream%26gt;
using namespace std;
int getNums(int %26amp;lower, int %26amp;upper);
int sum(int, int);
int main(){
int upper=0, lower=0, total=0;
getNums(lower, upper);
total = sum(upper, lower);
return 0;
}
int sum(int upper, int lower){
int total=0;
for(int i=lower; i%26lt;=upper; i++)
i+=total;
return total;
}
int sum(int %26amp;lower, int %26amp;upper){
cout %26lt;%26lt; "Type a lower and upper bounds:\n";
cin %26gt;%26gt; lower;
cin %26gt;%26gt; upper;
return 0;
}
Reply:In C++, to get this to compile you have a bad arrangement of braces that must be remedied. I'll show them in a better light below.
#include %26lt;iostream%26gt;
using namespace std;
int sum(void){//definition of function. { required.
int lower, upper;
cout %26lt;%26lt; " Enter a lower and upper bound: ";
cin %26gt;%26gt; lower %26gt;%26gt; upper;
int total = 0; //holds the total that will be //returned
for(int i = lower; i %26lt;= upper; i++){ //calculate the //total
total += i; //returns the total, which is the sum //25 (3 + 4 + 5 + 6 + 7)
}//end of for loop.
return total;
} // end of function sum.
int main(){
cout %26lt;%26lt; sum();
return 0;
}// end of main.
I've got it so it will compile, so start in from there and reread any material you've got on what demarcates a function in C/C++. I hope this helps. Pivy.
Syntax error in c++ program?
while () (ch=cin.get) ! =\n
Syntax error in c++ program?
while ( (ch = cin.get()) != '\n') { }
Reply:while ( (ch = cin.get) != \n) { }
Reply:while () (ch=cin.get) ! ="\n"
Syntax error in c++ program?
while ( (ch = cin.get()) != '\n') { }
Reply:while ( (ch = cin.get) != \n) { }
Reply:while () (ch=cin.get) ! ="\n"
What is wrong with this C++ program?
#include%26lt;iostream%26gt;
using namespace std;
int main()
{
int numCount, total;
double average;
cout %26lt;%26lt; "How many numbers do you want to average? ";
cin %26gt;%26gt; numCount;
for (int count = 0; count %26lt; numCount; count++)
{
int num;
cout %26lt;%26lt; "Enter a number: ";
cin %26gt;%26gt; num;
total += num;
}
average = total / numCount;
cout %26lt;%26lt; "The average is " %26lt;%26lt; average %26lt;%26lt; endl;
return 0;
}
What is wrong with this C++ program?
dude int total get initialized to garbage value..
so use
int numCount,total=0;
this should giv u the correct answer
#include%26lt;iostream%26gt;
using namespace std;
int main()
{
int numCount, total=0;
double average;
cout %26lt;%26lt; "How many numbers do you want to average? ";
cin %26gt;%26gt; numCount;
for (int count = 0; count %26lt; numCount; count++)
{
int num;
cout %26lt;%26lt; "Enter a number: ";
cin %26gt;%26gt; num;
total += num;
}
average = total / numCount;
cout %26lt;%26lt; "The average is " %26lt;%26lt; average %26lt;%26lt; endl;
return 0;
}
Reply:total/numCount is integer devided by integer wil result in fraction part truncated. Also all vaiables need to be initialized to 0.
Two Solutions
1. Use datatype casting: i.e., You can replace
average = total/numCount ;
with
average=(double)total / (double) numcount;
2. Initialize numcount and Total as double/float datatype
instead of integer.
Reply:It looks ok to me. The only thing I would suggest is initializing your variables to something so you know you don't have junk in them. So set numCount and total to 0 at the top and also set average to 0.0 and don't forget to set num = 0 in your for loop as well. I'm not sure exactly what the problem is or if there is one since you didn't mention a specific error.
Reply:Try placing the "int num;" outside of the for.
for total, make it "total = total + num;"
Remember to close everything, even "for" with a ";"
If this doesn't fix it, can you say what exactly the problem is when it runs?
It's been a long time since C++, sorry if I'm wrong.
augustifolia
using namespace std;
int main()
{
int numCount, total;
double average;
cout %26lt;%26lt; "How many numbers do you want to average? ";
cin %26gt;%26gt; numCount;
for (int count = 0; count %26lt; numCount; count++)
{
int num;
cout %26lt;%26lt; "Enter a number: ";
cin %26gt;%26gt; num;
total += num;
}
average = total / numCount;
cout %26lt;%26lt; "The average is " %26lt;%26lt; average %26lt;%26lt; endl;
return 0;
}
What is wrong with this C++ program?
dude int total get initialized to garbage value..
so use
int numCount,total=0;
this should giv u the correct answer
#include%26lt;iostream%26gt;
using namespace std;
int main()
{
int numCount, total=0;
double average;
cout %26lt;%26lt; "How many numbers do you want to average? ";
cin %26gt;%26gt; numCount;
for (int count = 0; count %26lt; numCount; count++)
{
int num;
cout %26lt;%26lt; "Enter a number: ";
cin %26gt;%26gt; num;
total += num;
}
average = total / numCount;
cout %26lt;%26lt; "The average is " %26lt;%26lt; average %26lt;%26lt; endl;
return 0;
}
Reply:total/numCount is integer devided by integer wil result in fraction part truncated. Also all vaiables need to be initialized to 0.
Two Solutions
1. Use datatype casting: i.e., You can replace
average = total/numCount ;
with
average=(double)total / (double) numcount;
2. Initialize numcount and Total as double/float datatype
instead of integer.
Reply:It looks ok to me. The only thing I would suggest is initializing your variables to something so you know you don't have junk in them. So set numCount and total to 0 at the top and also set average to 0.0 and don't forget to set num = 0 in your for loop as well. I'm not sure exactly what the problem is or if there is one since you didn't mention a specific error.
Reply:Try placing the "int num;" outside of the for.
for total, make it "total = total + num;"
Remember to close everything, even "for" with a ";"
If this doesn't fix it, can you say what exactly the problem is when it runs?
It's been a long time since C++, sorry if I'm wrong.
augustifolia
Sos, plz solve the errors c++(core)?
#include%26lt;iostream.h%26gt;
#include%26lt;conio.h%26gt;
main()
{
float a,b,sign;
cout%26lt;%26lt;"enter two numbers";
cin%26gt;%26gt;a%26gt;%26gt;b;
cout%26lt;%26lt;"choose a sign";
cin%26gt;%26gt;sign;
if (sign==1)
{sign=a*b;
cout%26lt;%26lt;sign;}
if (sign==2)
{sign=a+b;
cout%26lt;%26lt;sign;}
if (sign==3)
{sign=a/b;
cout%26lt;%26lt;sign;}
if (sign==4)
{sign=a-b;
cout%26lt;%26lt;sign;}
getch()
}
}
Sos, plz solve the errors c++(core)?
what kind of math is that??????????
ummmmmmm.................................
dont know sorry
Reply:#include%26lt;iostream.h%26gt;
#include%26lt;conio.h%26gt;
main()
{
float a,b,sign;
cout%26lt;%26lt;"enter two numbers";
cin%26gt;%26gt;a%26gt;%26gt;b;
cout%26lt;%26lt;"choose a sign";
cin%26gt;%26gt;sign;
if (sign==1)
{sign=a*b;
cout%26lt;%26lt;sign;}
if (sign==2)
{sign=a+b;
cout%26lt;%26lt;sign;}
if (sign==3)
{sign=a/b;
cout%26lt;%26lt;sign;}
if (sign==4)
{sign=a-b;
cout%26lt;%26lt;sign;}
cout%26lt;%26lt;flush;
getch();
}
// Note : you can remove cout%26lt;%26lt;flush; it forces the cout to write on the screen before the pause caused by getch();
Reply:Unless you can be more specific regarding an error (logical) ... as I do not understand the intent of the code other than the obvious ... there are two syntax errors :
(1) Missing semicolon after "getch()"
(2) An excess brace after the line mentioned above.
I would also clean up the code by using a simple switch statement and a few other minor adjustments, as follows :
#include %26lt;conio.h%26gt;
#include %26lt;iostream.h%26gt;
void main()
{
float a, b, result;
int operator;
cout %26lt;%26lt; "Enter two numbers :";
cin %26gt;%26gt; a;
cin %26gt;%26gt; b;
cout %26lt;%26lt; "Select an operator.";
cout %26lt;%26lt; "1. Multiplication";
cout %26lt;%26lt; "2. Addition";
cout %26lt;%26lt; "3. Division";
cout %26lt;%26lt; "4. Subtraction";
cin %26gt;%26gt; operator;
switch (operator)
{
case 1 :
result = (a * b);
break;
case 2 :
result = (a + b);
break;
case 3 :
result = (a / b);
break;
case 4 :
result = (a - b);
break;
}
cout %26lt;%26lt; "Result = " %26lt;%26lt; result;
getch();
}
#include%26lt;conio.h%26gt;
main()
{
float a,b,sign;
cout%26lt;%26lt;"enter two numbers";
cin%26gt;%26gt;a%26gt;%26gt;b;
cout%26lt;%26lt;"choose a sign";
cin%26gt;%26gt;sign;
if (sign==1)
{sign=a*b;
cout%26lt;%26lt;sign;}
if (sign==2)
{sign=a+b;
cout%26lt;%26lt;sign;}
if (sign==3)
{sign=a/b;
cout%26lt;%26lt;sign;}
if (sign==4)
{sign=a-b;
cout%26lt;%26lt;sign;}
getch()
}
}
Sos, plz solve the errors c++(core)?
what kind of math is that??????????
ummmmmmm.................................
dont know sorry
Reply:#include%26lt;iostream.h%26gt;
#include%26lt;conio.h%26gt;
main()
{
float a,b,sign;
cout%26lt;%26lt;"enter two numbers";
cin%26gt;%26gt;a%26gt;%26gt;b;
cout%26lt;%26lt;"choose a sign";
cin%26gt;%26gt;sign;
if (sign==1)
{sign=a*b;
cout%26lt;%26lt;sign;}
if (sign==2)
{sign=a+b;
cout%26lt;%26lt;sign;}
if (sign==3)
{sign=a/b;
cout%26lt;%26lt;sign;}
if (sign==4)
{sign=a-b;
cout%26lt;%26lt;sign;}
cout%26lt;%26lt;flush;
getch();
}
// Note : you can remove cout%26lt;%26lt;flush; it forces the cout to write on the screen before the pause caused by getch();
Reply:Unless you can be more specific regarding an error (logical) ... as I do not understand the intent of the code other than the obvious ... there are two syntax errors :
(1) Missing semicolon after "getch()"
(2) An excess brace after the line mentioned above.
I would also clean up the code by using a simple switch statement and a few other minor adjustments, as follows :
#include %26lt;conio.h%26gt;
#include %26lt;iostream.h%26gt;
void main()
{
float a, b, result;
int operator;
cout %26lt;%26lt; "Enter two numbers :";
cin %26gt;%26gt; a;
cin %26gt;%26gt; b;
cout %26lt;%26lt; "Select an operator.";
cout %26lt;%26lt; "1. Multiplication";
cout %26lt;%26lt; "2. Addition";
cout %26lt;%26lt; "3. Division";
cout %26lt;%26lt; "4. Subtraction";
cin %26gt;%26gt; operator;
switch (operator)
{
case 1 :
result = (a * b);
break;
case 2 :
result = (a + b);
break;
case 3 :
result = (a / b);
break;
case 4 :
result = (a - b);
break;
}
cout %26lt;%26lt; "Result = " %26lt;%26lt; result;
getch();
}
I have got a little broblem when i compile this c++ code could u help me?
#include%26lt;iostream.h%26gt;
#include%26lt;stdlib.h%26gt;
#define close
struct data{
char name[30];
int year;
}person [close];
int main()
{
char buffer [30];
int n;
cout%26lt;%26lt;"How many persons do u want to enter?";
cin.getline (buffer,30); close=atoi(buffer);
for (n=1;n%26lt;close;n++)
{
cout%26lt;%26lt;"Enter the name of the person: ";
cin.getline (person[n].name,30);
cout%26lt;%26lt;"How old is "%26lt;%26lt;person[n].name%26lt;%26lt;" ?";
cin.getline (buffer,30);person[n].year=atoi(buffer);
}
cout%26lt;%26lt;"The persons data u entered are as follows:\n";
for (n=1;n%26lt;close;n++)
{
cout%26lt;%26lt;person[n].name%26lt;%26lt;" is "%26lt;%26lt;person[n].year%26lt;%26lt;" year(s) old! \n";
}
return main();
}
i want the output to be like this:
how many persons do u eant to enter?
3
enter the name of the person: ben
how old is ben? 19
enter the name of the person: catherine
how old is catherine? 17
enter the name of the person: sophia
how old is sophia? 22
the persons data u entered are as follows:
ben is 19 years old
catherine is 17 years old
sophia is 22 year
I have got a little broblem when i compile this c++ code could u help me?
change three things
#define close
to
#define close 5
for (n=1;n%26lt;close;n++)
to
for (n=0;n%26lt;close;n++)
and
return main();
to
return 0;
then the program works
Reply:One major flaw that probably causes you error is
#define close
has no value also, it's constant you wont be able to change it
unless
#define close(x) x %26gt; 0 ? x : 0
then in your code you can do something like
close(atoi(buffer))
note: This will work like a function with a return value so you'll have to assign it
If you want user input then don't use a #define close
declare it local or global if you want because when you use #define it'll be constant and won't change
Reply:First, you want to change:
for (n=1;n%26lt;close;n++)
to:
for (n=0;n%26lt;close;n++)
Otherwise, it will ask for one less than what you wanted.
Also, you want to change:
return main();
to:
return true;
Otherwise, it will restart as soon as it finishes. (If you want it to automatically run again after it finishes printing, use a while loop like this:
....
int main()
{
while(true)
{
char buffer [30];
....
cout%26lt;%26lt;person[n].name%26lt;%26lt;" is "%26lt;%26lt;person[n].year%26lt;%26lt;" year(s) old! \n";
}
}
return true;
}
it will give the same result, but this is a much better programming style.
#include%26lt;stdlib.h%26gt;
#define close
struct data{
char name[30];
int year;
}person [close];
int main()
{
char buffer [30];
int n;
cout%26lt;%26lt;"How many persons do u want to enter?";
cin.getline (buffer,30); close=atoi(buffer);
for (n=1;n%26lt;close;n++)
{
cout%26lt;%26lt;"Enter the name of the person: ";
cin.getline (person[n].name,30);
cout%26lt;%26lt;"How old is "%26lt;%26lt;person[n].name%26lt;%26lt;" ?";
cin.getline (buffer,30);person[n].year=atoi(buffer);
}
cout%26lt;%26lt;"The persons data u entered are as follows:\n";
for (n=1;n%26lt;close;n++)
{
cout%26lt;%26lt;person[n].name%26lt;%26lt;" is "%26lt;%26lt;person[n].year%26lt;%26lt;" year(s) old! \n";
}
return main();
}
i want the output to be like this:
how many persons do u eant to enter?
3
enter the name of the person: ben
how old is ben? 19
enter the name of the person: catherine
how old is catherine? 17
enter the name of the person: sophia
how old is sophia? 22
the persons data u entered are as follows:
ben is 19 years old
catherine is 17 years old
sophia is 22 year
I have got a little broblem when i compile this c++ code could u help me?
change three things
#define close
to
#define close 5
for (n=1;n%26lt;close;n++)
to
for (n=0;n%26lt;close;n++)
and
return main();
to
return 0;
then the program works
Reply:One major flaw that probably causes you error is
#define close
has no value also, it's constant you wont be able to change it
unless
#define close(x) x %26gt; 0 ? x : 0
then in your code you can do something like
close(atoi(buffer))
note: This will work like a function with a return value so you'll have to assign it
If you want user input then don't use a #define close
declare it local or global if you want because when you use #define it'll be constant and won't change
Reply:First, you want to change:
for (n=1;n%26lt;close;n++)
to:
for (n=0;n%26lt;close;n++)
Otherwise, it will ask for one less than what you wanted.
Also, you want to change:
return main();
to:
return true;
Otherwise, it will restart as soon as it finishes. (If you want it to automatically run again after it finishes printing, use a while loop like this:
....
int main()
{
while(true)
{
char buffer [30];
....
cout%26lt;%26lt;person[n].name%26lt;%26lt;" is "%26lt;%26lt;person[n].year%26lt;%26lt;" year(s) old! \n";
}
}
return true;
}
it will give the same result, but this is a much better programming style.
Can someone please check my C++ program? please!!!?
ok. This program should display the string "Dog" when the animal variable catains the letter D (in any case); otherwise, it should display the string "Cat".
However, when i run it, it only displays the string "Cat" no matter what letter i type in it. WHY? this is my code:
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
//declare variable
char animal = ' ';
string ID = "";
//enter input
cout %26lt;%26lt; "Enter an animal ID: ";
cin %26gt;%26gt; ID;
//display ID
if (animal == 'D' || animal == 'd')
cout %26lt;%26lt; "Dog" %26lt;%26lt; endl;
else
cout %26lt;%26lt; "Cat" %26lt;%26lt; endl;
//end if
return 0;
} //end of main function
Can someone please check my C++ program? please!!!?
You never put anything in animal?
Your if needs to be checking ID == D or ID == d not animal. where does animal get its value? So right now animal doesn't have anything in it, and thus null ==D is false and the else statement is fired.
Reply:I agree with the ones above that say animal is still empty.
You can try printing it out to verify:
I think you are trying to check the first letter of ID, but you never copy it to your animal variable. Add the following line after your cin line:
animal = ( ID . c_str ( ) ) [0] ;
This copies the char to animal.
Reply:not if animal
use ID == 'D' || ID == 'd'
Reply:You don't need ID (and you can't test it's value using == anyway). Change:
cin %26gt;%26gt; ID;
to:
cin %26gt;%26gt; animal;
Reply:It seems to me you have your input set to the variable ID and then your if statement is using the variable animal which you have never assigned a value to.
So since animal = "" then the else case is always true and you always get cat.
Change the line cin %26gt;%26gt; ID to cin %26gt;%26gt; animal
Reply://Display ID section...
you;re using the variable ID to hold what letter they enter...
then at the point where you are going to display the result you're checking the variable animal not ID
change that to:
if (ID == 'D' || ID == 'd')
nobile
However, when i run it, it only displays the string "Cat" no matter what letter i type in it. WHY? this is my code:
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
//declare variable
char animal = ' ';
string ID = "";
//enter input
cout %26lt;%26lt; "Enter an animal ID: ";
cin %26gt;%26gt; ID;
//display ID
if (animal == 'D' || animal == 'd')
cout %26lt;%26lt; "Dog" %26lt;%26lt; endl;
else
cout %26lt;%26lt; "Cat" %26lt;%26lt; endl;
//end if
return 0;
} //end of main function
Can someone please check my C++ program? please!!!?
You never put anything in animal?
Your if needs to be checking ID == D or ID == d not animal. where does animal get its value? So right now animal doesn't have anything in it, and thus null ==D is false and the else statement is fired.
Reply:I agree with the ones above that say animal is still empty.
You can try printing it out to verify:
I think you are trying to check the first letter of ID, but you never copy it to your animal variable. Add the following line after your cin line:
animal = ( ID . c_str ( ) ) [0] ;
This copies the char to animal.
Reply:not if animal
use ID == 'D' || ID == 'd'
Reply:You don't need ID (and you can't test it's value using == anyway). Change:
cin %26gt;%26gt; ID;
to:
cin %26gt;%26gt; animal;
Reply:It seems to me you have your input set to the variable ID and then your if statement is using the variable animal which you have never assigned a value to.
So since animal = "" then the else case is always true and you always get cat.
Change the line cin %26gt;%26gt; ID to cin %26gt;%26gt; animal
Reply://Display ID section...
you;re using the variable ID to hold what letter they enter...
then at the point where you are going to display the result you're checking the variable animal not ID
change that to:
if (ID == 'D' || ID == 'd')
nobile
What is wrong with this C++ syntax?
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
using namespace std;
void convert(double numberSize, double current, string typeOF);
int main()
{
double number;
char measurement;
cout%26lt;%26lt; "Number\n%26gt;%26gt;";
cin %26gt;%26gt; number;
cout %26lt;%26lt; "Type\n%26gt;%26gt;";
cin %26gt;%26gt; measurement;
switch(measurement)
{
case "inches":
convert(0.083 333 333, number, "inches");
}
system ("pause");
return 0;
}
void convert(double numberSize, double current, string typeOF)
{
cout %26lt;%26lt; "Type: " %26lt;%26lt; typeOF %26lt;%26lt;
endl %26lt;%26lt; "Size: " %26lt;%26lt; numberSize * current;
}
What is wrong with this C++ syntax?
It looks like your variable "measurement" should be a character array instead of char. Then you use cin.getline to read it in. Finally you cannot use a switch statement with strings, so you would use an if statement.
Example:
char measurement[128];
std::cin.getline( measurement, 128);
std::string compareString;
compareString = measurement;
if(compareString.compare("inches") == 0)
{
// do stuff
}
Reply:Haven't done much C++ before but these lines:
cout%26lt;%26lt; "Number\n%26gt;%26gt;";
cout %26lt;%26lt; "Type\n%26gt;%26gt;";
should be,
cout%26lt;%26lt; "Number\n"%26gt;%26gt;;
cout %26lt;%26lt; "Type\n"%26gt;%26gt;;
The nesting of quotes is wrong at the moment.
Reply:Paraphrasing the compiler error in g++, "Case labels must be able to be reduced to an integer constant". "inches" is an array of chars. Your compiler probably should have given you an error.
If you use the 'char' type for your case labels, e.g. 'i', than it will work, however this limits you to single-letter input. If you really want to use strings, you can use a hash or a map to get an integer value from your known strings. It looks as if you're only altering a double (numberSize), so you can make a string to double map that will return the desired constant when you feed it a string, and scrap the switch. Something like:
struct CompStruct
{
bool operator()( const char* s1, const char* s2 ) const
{
return strcmp( s1, s2 ) %26lt; 0;
}
};
//inside main():
map%26lt;const char*, double, CompStruct%26gt; numberSizes;
numberSizes["inches"] = 0.083333333;
numberSizes["something"] = 0.123456789;
// etc.
string stringFromUser;
cin %26gt;%26gt; stringFromUser;
convert(numberSizes[stringFromUser], number, stringFromUser);
The syntax might be off, but I suppose it will work. Don't forget your error handling in case the key is not found.
#include %26lt;string%26gt;
using namespace std;
void convert(double numberSize, double current, string typeOF);
int main()
{
double number;
char measurement;
cout%26lt;%26lt; "Number\n%26gt;%26gt;";
cin %26gt;%26gt; number;
cout %26lt;%26lt; "Type\n%26gt;%26gt;";
cin %26gt;%26gt; measurement;
switch(measurement)
{
case "inches":
convert(0.083 333 333, number, "inches");
}
system ("pause");
return 0;
}
void convert(double numberSize, double current, string typeOF)
{
cout %26lt;%26lt; "Type: " %26lt;%26lt; typeOF %26lt;%26lt;
endl %26lt;%26lt; "Size: " %26lt;%26lt; numberSize * current;
}
What is wrong with this C++ syntax?
It looks like your variable "measurement" should be a character array instead of char. Then you use cin.getline to read it in. Finally you cannot use a switch statement with strings, so you would use an if statement.
Example:
char measurement[128];
std::cin.getline( measurement, 128);
std::string compareString;
compareString = measurement;
if(compareString.compare("inches") == 0)
{
// do stuff
}
Reply:Haven't done much C++ before but these lines:
cout%26lt;%26lt; "Number\n%26gt;%26gt;";
cout %26lt;%26lt; "Type\n%26gt;%26gt;";
should be,
cout%26lt;%26lt; "Number\n"%26gt;%26gt;;
cout %26lt;%26lt; "Type\n"%26gt;%26gt;;
The nesting of quotes is wrong at the moment.
Reply:Paraphrasing the compiler error in g++, "Case labels must be able to be reduced to an integer constant". "inches" is an array of chars. Your compiler probably should have given you an error.
If you use the 'char' type for your case labels, e.g. 'i', than it will work, however this limits you to single-letter input. If you really want to use strings, you can use a hash or a map to get an integer value from your known strings. It looks as if you're only altering a double (numberSize), so you can make a string to double map that will return the desired constant when you feed it a string, and scrap the switch. Something like:
struct CompStruct
{
bool operator()( const char* s1, const char* s2 ) const
{
return strcmp( s1, s2 ) %26lt; 0;
}
};
//inside main():
map%26lt;const char*, double, CompStruct%26gt; numberSizes;
numberSizes["inches"] = 0.083333333;
numberSizes["something"] = 0.123456789;
// etc.
string stringFromUser;
cin %26gt;%26gt; stringFromUser;
convert(numberSizes[stringFromUser], number, stringFromUser);
The syntax might be off, but I suppose it will work. Don't forget your error handling in case the key is not found.
Error in c++ program?
I'm trying to find the max of 10 numbers and I don't need to keep the number after I've checked to see if it is greater then the max. I'm going off the model my teacher gave me but it's not working and nothing I do helps.
int max=0;
int n1;
int i=0;
while(i %26lt; 10)
{
cout%26lt;%26lt;"Enter number"%26lt;%26lt;endl;
cin%26gt;%26gt;n1;
if (max%26lt;n1)
max=n1
i=i+1
}
cout%26lt;%26lt;"The maximum number is"%26lt;%26lt;max%26lt;%26lt;endl;
when I check I come up with
error: expected unqualified-id before awhilea
error: expected constructor, destructor, or type conversation before a%26lt;%26lt;a token
Error in c++ program?
You need to declare a main() function as an entry point, so the program knows where to start. ^_^
#include %26lt;iostream.h%26gt;
int main()
{
(your above code goes here)
}
Reply:int max=0;
int n1;
int i=0;
while(i %26lt; 10)
{
cout%26lt;%26lt;"Enter number"%26lt;%26lt;endl;
cin %26gt;%26gt; n1;
if (max %26lt; n1)
max = n1;
i=i+1;
}
cout %26lt;%26lt; "The maximum number is" %26lt;%26lt; max %26lt;%26lt;endl;
You had missed two ;
int max=0;
int n1;
int i=0;
while(i %26lt; 10)
{
cout%26lt;%26lt;"Enter number"%26lt;%26lt;endl;
cin%26gt;%26gt;n1;
if (max%26lt;n1)
max=n1
i=i+1
}
cout%26lt;%26lt;"The maximum number is"%26lt;%26lt;max%26lt;%26lt;endl;
when I check I come up with
error: expected unqualified-id before awhilea
error: expected constructor, destructor, or type conversation before a%26lt;%26lt;a token
Error in c++ program?
You need to declare a main() function as an entry point, so the program knows where to start. ^_^
#include %26lt;iostream.h%26gt;
int main()
{
(your above code goes here)
}
Reply:int max=0;
int n1;
int i=0;
while(i %26lt; 10)
{
cout%26lt;%26lt;"Enter number"%26lt;%26lt;endl;
cin %26gt;%26gt; n1;
if (max %26lt; n1)
max = n1;
i=i+1;
}
cout %26lt;%26lt; "The maximum number is" %26lt;%26lt; max %26lt;%26lt;endl;
You had missed two ;
Translating a code from C++ to Java...?
I need some help putting this code into Java
#include %26lt;iostream%26gt;
using namespace std;
int main() {
int sales[9]= { 0 };
double gross=0, percent=0, salary=0;
int total=0;
int counter=0;
cout %26lt;%26lt; "For 5 peoples salary ranges, Enter the first gross" %26lt;%26lt; endl;
cin %26gt;%26gt; gross;
percent=gross*0.09;
salary=200+percent;
while (counter!=5) {
if (salary%26gt;=200 %26amp;%26amp; salary %26lt;= 299)
sales[0]++;
if (salary%26gt;=300 %26amp;%26amp; salary%26lt;=399)
sales[1]++;
if (salary%26gt;400 %26amp;%26amp; salary%26lt;=499)
sales[2]++;
if (salary%26gt;=500 %26amp;%26amp; salary%26lt;=599)
sales[3]++;
if (salary%26gt;=600 %26amp;%26amp; salary%26lt;=699)
sales[4]++;
if (salary%26gt;=700 %26amp;%26amp; salary%26lt;=799)
sales[5]++;
if (salary%26gt;=800 %26amp;%26amp; salary%26lt;=899)
sales[6]++;
if (salary%26gt;=900 %26amp;%26amp; salary%26lt;=999)
sales[7]++;
if (salary%26gt;=1000)
sales[8]++;
cout %26lt;%26lt; "Enter the next gross" %26lt;%26lt; endl;
cin %26gt;%26gt; gross;
counter++;
}
cout %26lt;%26lt; sales[0] %26lt;%26lt; " are in 200-299, " %26lt;%26lt; sales[1] %26lt;%26lt; " are in 300-399, " %26lt;%26lt; sales[2] %26lt;%26lt; " are in 400-499, " %26lt;%26lt; sales[3] %26lt;%26lt; " are in 500-599, " %26lt;%26lt; sales[4]
Translating a code from C++ to Java...?
Declarations of variables and main() as well as imports are also different. You can also clean up your if statements to make them more efficent (one comparison instead of two).
This is a sample class that I called stest (in stest.java) that will illustrate how to use the scanner class to read from stdin (I left out all error checking and it will allow multiple gross values to be placed on a single input line which will result in unneeded prompts, but this is just a sample). It also illustrates how you can make one test instead of two in each of your if statements.
import java.util.*;
import java.lang.*;
import java.io.*;
class stest
{
public static void main( String argv[] )
{
int sales[]; // declaration; allocation is later
String range_names[] = { "200-299", "300-399", "400-499", "500-599", "600-699", "700-799", "800-899", "900-999", "%26gt;1000" };
Scanner s; // input scanner object
int need = 5; // number of values needed
double percent = 0; // percentage commission maybe?
double salary = 0; // persons computed salary
double gross = 0; // gross sales maybe?
int idx; // index into sales
sales = new int[9]; // allocate the array (Id name this salarycount or something relative)
s = new Scanner( System.in ); // read from standard input (assume keyboard)
while( need %26gt; 0 )
{
System.out.printf( "enter gross sales for person %d: ", 6-need );
gross = s.nextInt( ); // get next int value from stdin (no error checking here)
percent = gross * 0.09; // duplication of your logic
salary = 200.0 + percent; // duplication of your logic
if( salary %26gt;= 1000 ) // working backwards needs just one
idx = 8; // comparison so more efficent
else
if( salary %26gt;= 900 )
idx = 7;
else
if( salary %26gt;= 800 )
idx = 6;
else
if( salary %26gt;= 700 )
idx = 5;
else
if( salary %26gt;= 600 )
idx = 4;
else
if( salary %26gt;= 500 )
idx = 3;
else
if( salary %26gt;= 400 )
idx = 2;
else
if( salary %26gt;= 300 )
idx = 1;
else
idx = 0;
sales[idx]++;
need--; // one less to do
}
for( idx = 0; idx %26lt; 9; idx++ )
System.out.printf( "salaries in the range of %s: %d\n", range_names[idx], sales[idx] );
}
}
==== output when run with random numbers ====
java stest
enter gross sales for person 1: 3000
enter gross sales for person 2: 7000
enter gross sales for person 3: 24000
enter gross sales for person 4: 1200
enter gross sales for person 5: 1680
salaries in the range of 200-299: 0
salaries in the range of 300-399: 2
salaries in the range of 400-499: 1
salaries in the range of 500-599: 0
salaries in the range of 600-699: 0
salaries in the range of 700-799: 0
salaries in the range of 800-899: 1
salaries in the range of 900-999: 0
salaries in the range of %26gt;1000: 1
#include %26lt;iostream%26gt;
using namespace std;
int main() {
int sales[9]= { 0 };
double gross=0, percent=0, salary=0;
int total=0;
int counter=0;
cout %26lt;%26lt; "For 5 peoples salary ranges, Enter the first gross" %26lt;%26lt; endl;
cin %26gt;%26gt; gross;
percent=gross*0.09;
salary=200+percent;
while (counter!=5) {
if (salary%26gt;=200 %26amp;%26amp; salary %26lt;= 299)
sales[0]++;
if (salary%26gt;=300 %26amp;%26amp; salary%26lt;=399)
sales[1]++;
if (salary%26gt;400 %26amp;%26amp; salary%26lt;=499)
sales[2]++;
if (salary%26gt;=500 %26amp;%26amp; salary%26lt;=599)
sales[3]++;
if (salary%26gt;=600 %26amp;%26amp; salary%26lt;=699)
sales[4]++;
if (salary%26gt;=700 %26amp;%26amp; salary%26lt;=799)
sales[5]++;
if (salary%26gt;=800 %26amp;%26amp; salary%26lt;=899)
sales[6]++;
if (salary%26gt;=900 %26amp;%26amp; salary%26lt;=999)
sales[7]++;
if (salary%26gt;=1000)
sales[8]++;
cout %26lt;%26lt; "Enter the next gross" %26lt;%26lt; endl;
cin %26gt;%26gt; gross;
counter++;
}
cout %26lt;%26lt; sales[0] %26lt;%26lt; " are in 200-299, " %26lt;%26lt; sales[1] %26lt;%26lt; " are in 300-399, " %26lt;%26lt; sales[2] %26lt;%26lt; " are in 400-499, " %26lt;%26lt; sales[3] %26lt;%26lt; " are in 500-599, " %26lt;%26lt; sales[4]
Translating a code from C++ to Java...?
Declarations of variables and main() as well as imports are also different. You can also clean up your if statements to make them more efficent (one comparison instead of two).
This is a sample class that I called stest (in stest.java) that will illustrate how to use the scanner class to read from stdin (I left out all error checking and it will allow multiple gross values to be placed on a single input line which will result in unneeded prompts, but this is just a sample). It also illustrates how you can make one test instead of two in each of your if statements.
import java.util.*;
import java.lang.*;
import java.io.*;
class stest
{
public static void main( String argv[] )
{
int sales[]; // declaration; allocation is later
String range_names[] = { "200-299", "300-399", "400-499", "500-599", "600-699", "700-799", "800-899", "900-999", "%26gt;1000" };
Scanner s; // input scanner object
int need = 5; // number of values needed
double percent = 0; // percentage commission maybe?
double salary = 0; // persons computed salary
double gross = 0; // gross sales maybe?
int idx; // index into sales
sales = new int[9]; // allocate the array (Id name this salarycount or something relative)
s = new Scanner( System.in ); // read from standard input (assume keyboard)
while( need %26gt; 0 )
{
System.out.printf( "enter gross sales for person %d: ", 6-need );
gross = s.nextInt( ); // get next int value from stdin (no error checking here)
percent = gross * 0.09; // duplication of your logic
salary = 200.0 + percent; // duplication of your logic
if( salary %26gt;= 1000 ) // working backwards needs just one
idx = 8; // comparison so more efficent
else
if( salary %26gt;= 900 )
idx = 7;
else
if( salary %26gt;= 800 )
idx = 6;
else
if( salary %26gt;= 700 )
idx = 5;
else
if( salary %26gt;= 600 )
idx = 4;
else
if( salary %26gt;= 500 )
idx = 3;
else
if( salary %26gt;= 400 )
idx = 2;
else
if( salary %26gt;= 300 )
idx = 1;
else
idx = 0;
sales[idx]++;
need--; // one less to do
}
for( idx = 0; idx %26lt; 9; idx++ )
System.out.printf( "salaries in the range of %s: %d\n", range_names[idx], sales[idx] );
}
}
==== output when run with random numbers ====
java stest
enter gross sales for person 1: 3000
enter gross sales for person 2: 7000
enter gross sales for person 3: 24000
enter gross sales for person 4: 1200
enter gross sales for person 5: 1680
salaries in the range of 200-299: 0
salaries in the range of 300-399: 2
salaries in the range of 400-499: 1
salaries in the range of 500-599: 0
salaries in the range of 600-699: 0
salaries in the range of 700-799: 0
salaries in the range of 800-899: 1
salaries in the range of 900-999: 0
salaries in the range of %26gt;1000: 1
Load and save feature c++?
//load and save... i hope!!!
#include %26lt;iostream%26gt;
#include %26lt;fstream%26gt;
using namespace std;
int main()
{
system ("color 2B");
int choice;
int number;
cout %26lt;%26lt; "hi.\n\n\nContinue:1\nNew:2\n\n\n";
cin %26gt;%26gt; choice;
if (choice==2)
{ cout %26lt;%26lt; "\n\nEnter number.";
cin %26gt;%26gt; number;
cout %26lt;%26lt; "Number stored";
}
if (choice==1)
{
cout %26lt;%26lt; "\n\n\nYour number is: ";
cout %26lt;%26lt; number;
}
system ("PAUSE");
return 0;
}
How do I make it to where when the user restarts the program it will display the number they entered before? everytime i try to load a number i entered it always says 49. plzz post
Load and save feature c++?
It seems like you aren't trying to store anything in an fstream at all even though you included it. Just initialize an fstream and write to the same place each time. The 49 you see is probably an uninitialized variable that happens to have a 49 in it. It will be something else later.
hibiscus
#include %26lt;iostream%26gt;
#include %26lt;fstream%26gt;
using namespace std;
int main()
{
system ("color 2B");
int choice;
int number;
cout %26lt;%26lt; "hi.\n\n\nContinue:1\nNew:2\n\n\n";
cin %26gt;%26gt; choice;
if (choice==2)
{ cout %26lt;%26lt; "\n\nEnter number.";
cin %26gt;%26gt; number;
cout %26lt;%26lt; "Number stored";
}
if (choice==1)
{
cout %26lt;%26lt; "\n\n\nYour number is: ";
cout %26lt;%26lt; number;
}
system ("PAUSE");
return 0;
}
How do I make it to where when the user restarts the program it will display the number they entered before? everytime i try to load a number i entered it always says 49. plzz post
Load and save feature c++?
It seems like you aren't trying to store anything in an fstream at all even though you included it. Just initialize an fstream and write to the same place each time. The 49 you see is probably an uninitialized variable that happens to have a 49 in it. It will be something else later.
hibiscus
Subscribe to:
Posts (Atom)