Friday, July 31, 2009

C++ Error message?

Thanks for your previous answers. They've been eye-openers. I have a quick question. The program is to read from a file containing codes for vehicle types(perform the necessary conversions) and use the weights to perform calculations(multiplying by the user-entered tax values). Each line of the file contains the code and the weight. The weights should be integer values between 100 and 99000. Here's my input file








c 4000


t 20500


5 9000


m 500


b 10550


c 2500.8








I have a slight problem displaying the error message when a non-int value is encountered. I have tried several things with little success....Here is my output..











Enter the tax rate for MOTORCYCLES(0.01-0.99)


.25


Enter the tax rate for CARS(0.01-0.99)


45


Warning: entry invalid, rate must be between 0.01 and 0.99


Enter the tax rate for CARS(0.01-0.99)


.14


Enter the tax rate for BUSES(0.01-0.99)


89


Warning: entry invalid, rate must be between 0.01 and 0.99


Enter the tax rate for BUSES(0.01-0.99)


.28


Enter the tax rate for TRUCKS(0.01-0.99)


.26


ROAD TAX REPORT


Vehicle Type: Weight: Rate: Tax Due:





CAR 4000 0.14 560.00


TRUCK 20500 0.26 5330.00


5 9000 Error:Invalid Vehicle Code


MOTORCYCLE 500 0.25 125.00


BUS 10550 0.28 2954.00


CAR 2500 0.14 350.00


. 8 Error:Invalid Vehicle Code





It's made up of four columns(neatly arranged). As you can see, everything runs fine except for the last line. The desired output on the last row would be:


CAR 2500.8 Error: Invalid weight(non-integer)











Here is my program:














//Sample program to read input file and perform calculations with interactive values.


//Print out a table with input and calculated values.


#include%26lt;iostream%26gt;


#include%26lt;iomanip%26gt;


#include%26lt;fstream%26gt;


#include%26lt;cstring%26gt;


using namespace std;








void GetRates(float%26amp;, float%26amp;, float%26amp;, float%26amp;);





enum Vehicles{ERROR,MOTORCYCLE, CAR, BUS, TRUCK};











int main()





{


float cycleRate;


float carRate;


float busRate;


float truckRate;


char code;


int weight;


ifstream inFile;


Vehicles typeCode;














inFile.open("file1.dat");


if(!inFile)


{


cout%26lt;%26lt;"Unable to open input file, program abnormally ended"%26lt;%26lt;endl;


return 1;


}


GetRates(cycleRate, carRate, busRate, truckRate);


cout%26lt;%26lt;setw(40)%26lt;%26lt;" ROAD TAX REPORT"%26lt;%26lt;endl;


cout%26lt;%26lt;setw(2)%26lt;%26lt;"Vehicle Type:"%26lt;%26lt;setw(15)%26lt;%26lt;" Weight:"%26lt;%26lt;setw(15)%26lt;%26lt;" Rate:"%26lt;%26lt;setw(20)%26lt;%26lt;" Tax Due:"%26lt;%26lt;endl%26lt;%26lt;endl;





inFile%26gt;%26gt;code%26gt;%26gt;weight;


while(inFile)


{


{


if(!inFile)


cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision(2)%26lt;... Error:Invalid weight(non-integer)"%26lt;%26lt;endl; "Error: invalid weight(non-integer)";


}


{


if(code=='m')


typeCode=MOTORCYCLE;


else if(code=='c')


typeCode=CAR;


else if(code=='b')


typeCode=BUS;


else if(code=='t')


typeCode=TRUCK;


else


typeCode=ERROR;





}








switch(typeCode)


{


case MOTORCYCLE:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setpr...


break;


case CAR:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision...


break;


case BUS:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecision...


break;


case TRUCK:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecisi...


break;


case ERROR:cout%26lt;%26lt;fixed%26lt;%26lt;showpoint%26lt;%26lt;setprecisi... Error:Invalid Vehicle Code"%26lt;%26lt;endl;





}








inFile%26gt;%26gt;code%26gt;%26gt;weight;





}





cout%26lt;%26lt;endl;


cout%26lt;%26lt;"End of Report"%26lt;%26lt;endl;


return 0;


}























void GetRates(/*out*/ float%26amp; motorcycleRate,


/*out*/ float%26amp; carsRate,


/*out*/ float%26amp; busesRate,


/*out*/ float%26amp; trucksRate)


{








bool invalidData;


invalidData=true;


while(invalidData)


{


cout%26lt;%26lt;"Enter the tax rate for MOTORCYCLES(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;motorcycleRate;





{





if(0.009%26lt;=motorcycleRate%26amp;%26amp;motorcycleRate...


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{





cout%26lt;%26lt;"Enter the tax rate for CARS(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;carsRate;


{


if(0.009%26lt;=carsRate%26amp;%26amp;carsRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{


cout%26lt;%26lt;"Enter the tax rate for BUSES(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;busesRate;


{





if(0.009%26lt;=busesRate%26amp;%26amp;busesRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}


}


invalidData=true;


while(invalidData)


{





cout%26lt;%26lt;"Enter the tax rate for TRUCKS(0.01-0.99)"%26lt;%26lt;endl;


cin%26gt;%26gt;trucksRate;


{





if(0.009%26lt;=trucksRate%26amp;%26amp;trucksRate%26lt;=0.999)


invalidData=false;





else





cout%26lt;%26lt;"Warning: entry invalid, rate must be between 0.01 and 0.99"%26lt;%26lt;endl;





}








}





}














THANKS for your time!!

C++ Error message?
Your program is working fine, it is doing exactly what you want it to do.





The problem is that you are asking it to do the wrong thing.





The line with the problem is your input line.


inFile%26gt;%26gt;code%26gt;%26gt;weight





inFile knows that weight is a declared integer, so it is only reading an integer - that is, up to the decimal place. It is then processing that input.





When it returns again, it reads the ".8" as the code variable and returning the TypeCode Error.





You need to rethink the input statement in two ways: (1) you don't want to tell the input stream that it "weight" an integer, because that is all it will get; and (2) you want to check how code gets input so it only reads in one character.





I am not going to solve it for you - but that is where the problem is.
Reply:too long still thanks for the two points
Reply:I can't tell you what isn't working, but I can point out a prolem that may help you find it. When programming a structured or procedural (same thing, different names) program in any language one of the main goals is to make the code clear, readable, compact and well documented. I'm not able to see what delineations you've made between functions, count the functions or even trace the code effectively at this point. Do yourself a favor, take a break, relax and then look at the code you've written again and clean it up. You'll likely find your own problem in the clean up effort. It'll likely be a forehead smacker.

our song

String manipulation C++?

Hi i am working on a small program where a user enters a string which should be more than 8 characters. Then once they have entered a string, the program should do the following:


1) output the size of the sentence


2) output the 1st 3rd 5th and 7th letter and append it to the end of the inputted sentence.





This is what i have done so far but i am getting errors and i am new to c++:





#include %26lt;iostream%26gt;


#include %26lt;string.h%26gt;


#include %26lt;sstream%26gt;


using namespace std;





int main()


{


int iQuit;


char str[7];


cout%26lt;%26lt; "Enter sentence \n";


getline(cin,str);


cout%26lt;%26lt; "Size of the sentence" %26lt;%26lt; str.length() %26lt;%26lt; endl;


cin %26gt;%26gt; iQuit;


return 0;


}





Can someone help on this and the second part please? i could probably do this in java but i need to do in C++.





I would appreciate it if someone can help me on tell me they have done in such a way?

String manipulation C++?
There are two main kinds of string in C++, the null terminated strings inherited from C and the C++ string object. Using the latter makes your assignment a cinch. Unless you are instructed otherwise you should begin to use string objects and move away from null terminated strings whenever possible.








#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main()


{


string input;





while (input.length() %26lt;= 8)


{


cout%26lt;%26lt; "Enter sentence at least 8 characters in length\n";





getline(cin, input);


}





cout%26lt;%26lt; "Size of the sentence = " %26lt;%26lt; input.length() %26lt;%26lt; endl;





input += input[2];


input += input[4];


input += input[6];





cout %26lt;%26lt; "appended sentence is: " %26lt;%26lt; input %26lt;%26lt; endl;





return(0);


}
Reply:Try this code for starters. Can you spot the changes?





#include %26lt;iostream%26gt;


#include %26lt;string.h%26gt;


#include %26lt;sstream%26gt;


using namespace std;





int main()


{


int iQuit;


string input;


cout%26lt;%26lt; "Enter sentence \n";


getline(cin, input);


cout%26lt;%26lt; "Size of the sentence " %26lt;%26lt; input.length() %26lt;%26lt; endl;


cin %26gt;%26gt; iQuit;


return 0;


}
Reply:You can't say str.length(). You have to use the function strlen(), like this:





cout%26lt;%26lt; "Size of the sentence" %26lt;%26lt; strlen(str) %26lt;%26lt; endl;





To output the 1st, 3rd, 5th and 7th letters you have to access them from the string/character-array. This is done like so: str[0] is the 1st. str[2] is the 3rd letter, etc.





Appending is easy. Just make a new character array that is bigger, copy the inputted string to it (using the strcpy function) and then assign the letters that you want to the new string.


Please help me rewrite this poker game C++ code and make it work...?

#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;time.h%26gt;





using namespace std;





class cCard


{


public:


char face[13] = {'2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'};


enum suit[4] = {"S", "H", "D", "C"};


int getSuit ();


int getFace();


void print();


};


int cCard::getSuit()


{


return suit;


}


int cCard::getFace()


{


return face;


}


void cCard::print()


{


std::cout%26lt;%26lt;face %26lt;%26lt;suit;


}





class cDeck


{


public:


void shuffle();


char Card[13][4];


void Deck;


};


void cDeck::shuffle()


{


int face, suit;


for(face = 2; face %26lt; 13; face++)


{


for(suit = 0; suit %26lt; 4; suit++)


Card[face][suit] = NULL;


}


}


void cDeck::Deck()


{


int card, suit, face;


int deck[deckSuit][deckFace];


card = 1 ;


for (suit = 0 ; suit %26lt;= deckSuit - 1 ; suit++ )


{


for (face = 0 ; face %26lt;= deckFace - 1 ; face++ )


{


deck[suit][face] = card ;


card++;


}


}


}





class cPlayer


{


public:


string cPlayer();


void printHand();


void print();


};


string cPlayer::cPlayer(string name, int stake)


{


playerName = name;


playerStake = stake;


}


void cPlayer::printHand()


{


std::cout%26lt;%26lt;Card%26lt;%26lt;"\tab"%26lt;%26lt;Card%26lt;...


}


void cPlayer::print()


{


cout%26lt;%26lt;name %26lt;%26lt;" $" %26lt;%26lt;stake %26lt;%26lt;"\n";


}





class cGame


{


public:


bool addPlayer();


void play();


void deal();


void cardQuality();


void print();


};


bool cGame::addPlayer(string playerName, int playerStake)


{


std::cout %26lt;%26lt; "Enter your name: ";


std::cin %26gt;%26gt; playerName;


std::cout %26lt;%26lt; "\nHow much money you have for the game? ";


std::cin %26gt;%26gt; playerStake;


}


void cGame::play(int player[][2] , int shuffledCard[][13])


{


int sCard, sSuit, sFace, pSuit = 0 , pFace = 0;


static int cardStart = 1;





for (sCard = cardStart ; sCard %26lt;= cardStart + 4; sCard++ ) {


for (sSuit = 0 ; sSuit %26lt;= 3; sSuit++ ){


for(sFace = 0 ; sFace %26lt;= 12; sFace++ ){


if (shuffledCard[sSuit][sFace] == sCard ){


player[pSuit][pFace] = sSuit;


pFace++;


player[pSuit][pFace] = sFace;


pFace--;


pSuit++;








}


}


}


}


cardStart = sCard;





}


void cGame::deal(int playerHand[][2], const char *suit1[], const char *face1[])


{


int a , b;


for ( a = 0 ; a %26lt;= 4; a++ )


{


b = 0;


std::cout%26lt;%26lt;"%s"%26lt;%26lt;suit1[playerH...


b = 1;


std::cout%26lt;%26lt;"%s "%26lt;%26lt;face1[playerHand[a][b]]);


}


}


void cGame::whatHand( int playerHand [][2] )


{





int x,y;


int positFace[5], positSuit[5];


int *fPtr = positFace, *sPtr = positSuit ;


int Facepass = 0;


int Suitpass = 0 ;


int straight = 0;


for ( x = 0 ; x %26lt;= 4 ; x++ )


{


y = 1 ;


*fPtr = playerHand[x][y];


fPtr++ ;


}


for ( x = 0 ; x %26lt;= 4 ; x++ )


{


y = 0 ;


*sPtr = playerHand[x][y];


sPtr++ ;


}





for ( x = 0 ; x %26lt;= 3 ; x++ )


{


for ( y = (x + 1); y %26lt;= 4 ; y++ )


{


if ( *(positFace + x ) == *(positFace + y ) )


{


Facepass++;


}


}


}


for ( y = 0 ; y %26lt;= 3 ; y++ )


{


for (x = 0 ; x %26lt;= 3 ; x++ )


{


if ( positFace[x] %26gt; positFace[x+1] )


{


Swap(%26amp;positFace[x],%26amp;positFace[...


}


}


}


for ( y = 0; y %26lt;= 3 ; y++ )


{


if ( positFace[y] == positFace[y + 1] - 1 )


{


straight++;


}


}


for ( y = 1; y %26lt;= 4 ; y++ )


{


if ( *positSuit == *(positSuit + y ) )


{


Suitpass++;


}


}


switch ( Facepass )


{


case 1 :


std::cout%26lt;%26lt;"This poker hand contains a pair\n";


break ;


case 2 :


std::cout%26lt;%26lt;"This poker hand contains two pairs\n";


break;


case 3 :


std::cout%26lt;%26lt;"This poker hand contains three of a kind\n";


break ;


case 4:


std::cout%26lt;%26lt;"This poker hand contains a full house\n";


break ;


case 6:


std::cout%26lt;%26lt;"This poker hand contains four of a kind\n";


break ;


default :


if ( Suitpass == 4 %26amp;%26amp; straight != 4)


{


std::cout%26lt;%26lt;"This poker hand contains a flush\n";





}


if ( straight == 4 %26amp;%26amp; Suitpass != 4)


{


std::cout%26lt;%26lt;"This poker hand contains a straight\n";


}


if ( straight == 4 %26amp;%26amp; Suitpass == 4)


{


std::cout%26lt;%26lt;"This poker hand contains a straight flush\n";


}


break;


}


}





int main()


{


cPlayer thisplayer(Play#1, 1000);


thisplayer.print();


deck[4][13];


shuffle(deck, deckFace, deckSuit);


play(Play#1, deck);


deal(Play#1, suit, face);


whatHand(Play#1);


cPlayer thisplayer(Play#2, 1000);


thisplayer.print();


deck[4][13];


shuffle(deck, deckFace, deckSuit);


play(Play#2, deck);


deal(Play#2, suit, face);


whatHand(Play#2);


cPlayer thisplayer(Play#3, 1000);


thisplayer.print();


deck[4][13];


shuffle(deck, deckFace, deckSuit);


play(Play#3, deck);


deal(Play#3, suit, face);


whatHand(Play#3);


addPlayer thisplayer();


thisplayer.print();


deck[4][13];


shuffle(deck, deckFace, deckSuit);


play(playerName, deck);


deal(playerName, suit, face);


whatHand(playerName);


return 0;


}

Please help me rewrite this poker game C++ code and make it work...?
Sorry dude no time.
Reply:what error did your compiler give you?


Can somebody please help me with this C++ code?

#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;time.h%26gt;





using namespace std;





class cCard


{


public:


char face[13] = {'2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'};


enum suit[4] = {"S", "H", "D", "C"};


int getSuit ();


int getFace();


void print();


};


int cCard::getSuit()


{


return suit;


}


int cCard::getFace()


{


return face;


}


void cCard::print()


{


std::cout%26lt;%26lt;face %26lt;%26lt;suit;


}





class cDeck


{


public:


void shuffle();


char Card[13][4];


void Deck;


};


void cDeck::shuffle()


{


int face, suit;


for(face = 2; face %26lt; 13; face++)


{


for(suit = 0; suit %26lt; 4; suit++)


Card[face][suit] = NULL;


}


}


void cDeck::Deck()


{


int card, suit, face;


int deck[deckSuit][deckFace];


card = 1 ;


for (suit = 0 ; suit %26lt;= deckSuit - 1 ; suit++ )


{


for (face = 0 ; face %26lt;= deckFace - 1 ; face++ )


{


deck[suit][face] = card ;


card++;


}


}


}





class cPlayer


{


public:


string cPlayer();


void printHand();


void print();


};


string cPlayer::cPlayer(string name, int stake)


{


playerName = name;


playerStake = stake;


}


void cPlayer::printHand()


{


std::cout%26lt;%26lt;Card%26lt;%26lt;"\tab"%26lt;%26lt;Card%26lt;%26lt;"\tab"%26lt;%26lt;C...


}


void cPlayer::print()


{


cout%26lt;%26lt;name %26lt;%26lt;" $" %26lt;%26lt;stake %26lt;%26lt;"\n";


}





class cGame


{


public:


bool addPlayer();


void play();


void deal();


void cardQuality();


void print();


};


bool cGame::addPlayer(string playerName, int playerStake)


{


std::cout %26lt;%26lt; "Enter your name: ";


std::cin %26gt;%26gt; playerName;


std::cout %26lt;%26lt; "\nHow much money you have for the game? ";


std::cin %26gt;%26gt; playerStake;


}


void cGame::play(int player[][2] , int shuffledCard[][13])


{


int sCard, sSuit, sFace, pSuit = 0 , pFace = 0;


static int cardStart = 1;





for (sCard = cardStart ; sCard %26lt;= cardStart + 4; sCard++ ) {


for (sSuit = 0 ; sSuit %26lt;= 3; sSuit++ ){


for(sFace = 0 ; sFace %26lt;= 12; sFace++ ){


if (shuffledCard[sSuit][sFace] == sCard ){


player[pSuit][pFace] = sSuit;


pFace++;


player[pSuit][pFace] = sFace;


pFace--;


pSuit++;








}


}


}


}


cardStart = sCard;





}


void cGame::deal(int playerHand[][2], const char *suit1[], const char *face1[])


{


int a , b;


for ( a = 0 ; a %26lt;= 4; a++ )


{


b = 0;


std::cout%26lt;%26lt;"%s"%26lt;%26lt;suit1[playerHand[a][b]]...


b = 1;


std::cout%26lt;%26lt;"%s "%26lt;%26lt;face1[playerHand[a][b]]);


}


}


void cGame::whatHand( int playerHand [][2] )


{





int x,y;


int positFace[5], positSuit[5];


int *fPtr = positFace, *sPtr = positSuit ;


int Facepass = 0;


int Suitpass = 0 ;


int straight = 0;


for ( x = 0 ; x %26lt;= 4 ; x++ )


{


y = 1 ;


*fPtr = playerHand[x][y];


fPtr++ ;


}


for ( x = 0 ; x %26lt;= 4 ; x++ )


{


y = 0 ;


*sPtr = playerHand[x][y];


sPtr++ ;


}





for ( x = 0 ; x %26lt;= 3 ; x++ )


{


for ( y = (x + 1); y %26lt;= 4 ; y++ )


{


if ( *(positFace + x ) == *(positFace + y ) )


{


Facepass++;


}


}


}


for ( y = 0 ; y %26lt;= 3 ; y++ )


{


for (x = 0 ; x %26lt;= 3 ; x++ )


{


if ( positFace[x] %26gt; positFace[x+1] )


{


Swap(%26amp;positFace[x],%26amp;positFace[x+1]);


}


}


}


for ( y = 0; y %26lt;= 3 ; y++ )


{


if ( positFace[y] == positFace[y + 1] - 1 )


{


straight++;


}


}


for ( y = 1; y %26lt;= 4 ; y++ )


{


if ( *positSuit == *(positSuit + y ) )


{


Suitpass++;


}


}


switch ( Facepass )


{


case 1 :


std::cout%26lt;%26lt;"This poker hand contains a pair\n";


break ;


case 2 :


std::cout%26lt;%26lt;"This poker hand contains two pairs\n";


break;


case 3 :


std::cout%26lt;%26lt;"This poker hand contains three of a kind\n";


break ;


case 4:


std::cout%26lt;%26lt;"This poker hand contains a full house\n";


break ;


case 6:


std::cout%26lt;%26lt;"This poker hand contains four of a kind\n";


break ;


default :


if ( Suitpass == 4 %26amp;%26amp; straight != 4)


{


std::cout%26lt;%26lt;"This poker hand contains a flush\n";





}


if ( straight == 4 %26amp;%26amp; Suitpass != 4)


{


std::cout%26lt;%26lt;"This poker hand contains a straight\n";


}


if ( straight == 4 %26amp;%26amp; Suitpass == 4)


{


std::cout%26lt;%26lt;"This poker hand contains a straight flush\n";


}


break;


}


}





int main()


{


cPlayer thisplayer(Play#1, 1000);


thisplayer.print();


deck[4][13];


shuffle(deck, deckFace, deckSuit);


play(Play#1, deck);


deal(Play#1, suit, face);


whatHand(Play#1);


cPlayer thisplayer(Play#2, 1000);


thisplayer.print();


deck[4][13];


shuffle(deck, deckFace, deckSuit);


play(Play#2, deck);


deal(Play#2, suit, face);


whatHand(Play#2);


cPlayer thisplayer(Play#3, 1000);


thisplayer.print();


deck[4][13];


shuffle(deck, deckFace, deckSuit);


play(Play#3, deck);


deal(Play#3, suit, face);


whatHand(Play#3);


addPlayer thisplayer();


thisplayer.print();


deck[4][13];


shuffle(deck, deckFace, deckSuit);


play(playerName, deck);


deal(playerName, suit, face);


whatHand(playerName);


return 0;


}

Can somebody please help me with this C++ code?
this is one issue


enum suit[4] = {"S", "H", "D", "C"}; %26lt;---not an int


int cCard::getSuit()


{


return suit; %26lt;--returning an int


}


******


additional


looked further down realized your next one also returned an int when what you had was a char
Reply:what's the problem?


Trimming whitespace in C++?

I'm in an introductory course to C++, and I'm almost done writing a program. I'm having problems with one function though. It's supposed to trim all whitespace (not just that at the beginning and end--all spaces and tabs). This is what I have:





char* str_trim(char* str)


{


char* trim;





for(str; *str != '\0'; str++)


{


if(*str != ' ' %26amp;%26amp; *str != '\t')


{


trim = str;


trim++;


}


}





strcat(trim, '\0');


str = trim;





return str;


}





The program compiles, but this function (fine without it) is causing a Windows error message requires the command prompt to close. I've been over and over it, but I cannot figure out what is wrong. I would be grateful for any input. Thanks!

Trimming whitespace in C++?
Many ways to do this, but I'll use your code as a foundation





char* str_trim(char* str)


{


char* trim=str;





while(*trim)


{


if(*trim == ' ' || *trim == '\t') {


strcpy(trim,trim+1);


} else {


trim++;


}


}





return str;


}
Reply:kathryn,





Glad to see it. I didn't mean to give you a hard time, but it seems like many people get answers and forget to select a best answer. BTW, something has been weird with Yahoo lately. That might explain the delay. Report It

Reply:Hey dude





i have tried to create a prog it works what u r trying to do with urs.





#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;string.h%26gt;


#define max 100


void str_trim(char* str){


char trim[max];


int i;


for(str,i=0; *str != '\0'; str++){


if(*str != ' '){


trim[i] = *str;


i++;


}


}


puts(trim);


}





void main(){


clrscr();


char c[max];


gets(c);


str_trim(c);


getch();


}





check this prog and let me know if this works....ok





and one more thing man


in your prog one problem that i have seen is





in trim = str;


this line actually equals the whole string what we have enterd


in str to trim so.


pointer stroes address so if u will equate one pointer to other as a = b it will stores the to which b is pointing in a.





so it will not work to do ur task u have to work on values.


ok





i think it will work





bye..
Reply:kathryn,





If you appreciate Duane's answer, you might want to select his as the best answer to give him proper credit (and points). ;-)
Reply:looks okay. I dont see any problem.

flower pots

C++ help please?

i was making a a title on my program "tictactoe", when i run the program it was okey but when i compile it the error states that:





linker error: undefined symbol _main in module c0.ASM





here is my program:





#include%26lt;graphics.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;DOS.h%26gt;


#include%26lt;iostream.h%26gt;


#include%26lt;stdlib.h%26gt;


#include%26lt;stdio.h%26gt;








void gdriver(void);


void title(void);


void name(void);





char p1[16],p2[16];


void main()


{gamesequence();}


void gdriver(void)


{int gd=DETECT,gm;


initgraph(%26amp;gd,%26amp;gm,"c:/tc3/BGI");


}





void name()


{title();


setcolor(BLUE);


settextstyle(2,0,6);


outtextxy(205,180,"Please enter your names:");


setfillstyle(SOLID_FILL,RED);


bar(150,250,getmaxx()-150,getmaxy()-15...


gotoxy(21,17);


cout%26lt;%26lt;"Player 1:";


gotoxy(31,17);





cin%26gt;%26gt;p1;


gotoxy(21,19);


cout%26lt;%26lt;"player 2:";


gotoxy(31,19);


cin%26gt;%26gt;p2;


}








void title(void)


{clrscr();


char msg[50];


setcolor(4);


rectangle(628,200,0,0);


setcolor(3);


settextstyle(SANS_SERIF_FONT, HORIZ_DIR,9);


sprintf(msg,"TICTACTOE",9);


outtextxy(95,30,msg);


getch();


closegraph();}

C++ help please?
UNDEFINED SYMBOL: '_main' IN MODULE C0.ASM:





Every C program must contain a function called main(). This is the first function executed in your program. The function name must be all in lower case. If your program does not have one, create one. If you are using multiple source files, the file that contains the function main() must be one of the files listed in the project. Note that an underscore character '_' is prepended to all external Turbo C++ symbols. In addition to an absent, misspelled or mis-cased symbol main, there are two additional common causes: The "generate underbars" option is disabled. The Pascal calling Convention rather than the C calling convention is selected.





From the code I think you are getting that error possibly because of this reason:





"...If you are using multiple source files, the file that contains the function main() must be one of the files listed in the project..."
Reply:Text from vmlinux.org


http://www.vmlinux.org/~jakov/community....





UNDEFINED SYMBOL: '_main' IN MODULE C0.ASM


Every C program must contain a function called main().


This is the first function executed in your program.


The function name must be all in lower case. If your


program does not have one, create one. If you are


using multiple source files, the file that contains


the function main() must be one of the files listed in


the project.


Note that an underscore character '_' is prepended to


all external Turbo C++ symbols.


In addition to an absent, misspelled or mis-cased


symbol main, there are two additional common causes:


The "generate underbars" option is disabled.


The Pascal calling Convention rather than the C


calling convention is selected.
Reply:Do you have the gamesequence() function written somewhere? Or is it part of one of the libraries?





Source [1]:


UNDEFINED SYMBOL: '_main' IN MODULE C0.ASM


Every C program must contain a function called main().


This is the first function executed in your program.


The function name must be all in lower case. If your


program does not have one, create one. If you are


using multiple source files, the file that contains


the function main() must be one of the files listed in


the project.


Note that an underscore character '_' is prepended to


all external Turbo C++ symbols.


In addition to an absent, misspelled or mis-cased


symbol main, there are two additional common causes:


The "generate underbars" option is disabled.


The Pascal calling Convention rather than the C


calling convention is selected.





Source [2]:


Make sure that your program has a main() function defined. Secondly,


make sure that you're using the correct project setting (i.e., Console


Application). Then recompile your code and see if that solves the


problem.





Source [3]:


void main() is not legal in C++ but is legal in C.
Reply:In you main routine you calling a function





void main()


{gamesequence();}





which is not defined or protoyped before main()
Reply:try gamedev.net. there is a free chatroom there where u can get help from a lot of people. you could even post ur code on the live chatroom and they will help you.


Help with C++ Programming?

Below is my first C++ Program I have written for my C++ class. I compiled it and it said there was a problem concerning my forloop. Am I allowed to have a forloop inside an IF statement? Any help or tips would help alot. Explanation necessary. Redirecting me to an outside website won't do.





#include %26lt;iostream%26gt;


using namespace std;





int main()





{


char letter, confirm, x;


cout %26lt;%26lt; "What is your favorite letter?:\n";


cin %26gt;%26gt; letter;


cin.ignore();


cout %26lt;%26lt; "You chose ";


cout %26lt;%26lt; letter;


cout %26lt;%26lt; " as your favorite letter.\n";


cout %26lt;%26lt; "Are you sure? (Y=1/N=2)\n";


cin %26gt;%26gt; confirm;


if ( confirm == 2 ) {


for ( char x = 0; x %26lt; 1; x++ );


}


else {


cout %26lt;%26lt; "I like ";


cout %26lt;%26lt; letter;


cout %26lt;%26lt; " too. Thanks for playing.\n";


}


system ("pause");


}

Help with C++ Programming?
Next time it would be helpful to post the actual compiler error.





Your program compiled fine for me using gcc but you do have some logic errors.





(1) Your for loop doesn't actually do anything so you need to code an action for it. Using char x is fine by the way. A char is a valid numeric type to use in a loop.





(2) Your if statement will always be false. You are reading in type char for either 1 or 2 but your if statement is comparing against an int value. You need to change it to





if (confirm == '2')
Reply:Yes you are. But, your not allowed to declare x as a character.





for (int x = 0; x %26lt; 1; x++) {


/* your code */


}
Reply:Actually what happens when u store 0 in x is it stores ascii value of 0 in x that is 48 . when it checks x%26lt;1 which it checks 42%26lt;1... which does not satisfy ...


Solution


use x as integer


or


check the condition as x%26lt;'1'


C Programming error message?

C Programming error?





Hi, just started programming in C for uni.


Here's the relevant part of the program:





#define SIZE 100


{ int day_n, dayn;


char day[SIZE];


...


day_n = %26lt;some function%26gt;;


dayn = day_n%7;





if (dayn==0) day="Saturday";


else if (dayn==1) day="Sunday";


%26lt;etc%26gt;





printf("The day is a %c\n", day)


}





I keep getting error for each line with day in it:


left operand must be modifiable lvalue: op "="


I don't know what this means, or how to fix it, please help!


(I know this isn't the best way of writing it, but I can't be bothered to use a switch statement now!)

C Programming error message?
You can't copy a string like that.


look up strcpy().





Or, do something like this.


if(dayn==0)


printf("The day is Saturday")


if(dayn==1)


printf("The day is Sunday")
Reply:day_n and dayn are integers





enum {SATURDAY,SUNDAY...FRIDAY};





if(day_n == SATURDAY) // the enumerated value of SATURDAY is 0


strcpy(day,"SATURDAY"); // NOTE quoted string is not an integer


if(day_n == SUNDAY) // the enumerated value of SUNDAY is 1


strcpy(day,"SUNDAY");





etc...





?cant be bothered with a switch?





tm_horton@yahoo.com as I can help


Can someone please help me with a c++ program?

this c++ program is supposed to read in information about students from a file, calculate gpa and stuff and print it out, when i run the program i have all i get are weird outputs, help me figure this out plz





anyway heres the program





#include%26lt;iostream%26gt;


#include%26lt;string%26gt;


#include%26lt;fstream%26gt;





using namespace std;





class Course{


char grade;


int hours;


public:





Course(){


name = "";


hours = 0;


}


Course(string n, char g, int h);





void setName(string n){name=n;}


void setGrade(char g){grade=g;}


void setHours(int h){hours=h;}





string getName(){return name;}


char getGrade(){return grade;}


int getHours(){return hours;}





void print(){


if (name != ""){


cout.width(10); cout%26lt;%26lt; name;


cout.width(4); cout %26lt;%26lt; grade;


cout.width(4); cout %26lt;%26lt; hours %26lt;%26lt; endl;


}


else


cout %26lt;%26lt; "....." %26lt;%26lt; endl;


}


};


class Student{


string last,first,street,city,state,z...


int id;


int num_classes;


Course classes[15];

Can someone please help me with a c++ program?
You are not trying to debug this much, are you?





Isolate EACH of the modules. Add COUT statements to check the progress of EACH module, before and after. Is it getting the right input? Is it producing the right output?





If you're sure this module is working, but the module calling this module is not working, then the problem is with the caller.





Isolate and identify the problem one step at a time.
Reply:Going to need more info than this, particularly the input and the output that is mangled. Better yet, since you know this inside and out, you should debug this either by carpet-bombing your code with cout statements or using a debugger, either gdb (if you're on UNIX) or an IDE like MSVC++ Express.
Reply:First find a compiler that is compatible with your operating system, and decide whether you want to run an Integrated Development Environment (IDE) or if you want to edit C files manually through an editor like Notepad and compile from the command line. If you're a Window user, try using Visual C++ Express 2005 which is available for download for free. If you're a Unix user, you might just want to use gcc.


Learn how to compile and run a basic program, this will be your first program, typically it will just print "Hello World" to the screen and exit. Don't worry about all the minor details of the syntax, just become comfortable with compiling and running.


Learn about variable types, such as the difference between char, int, float, double, etc.


Learn about the concept of variables, arrays and functions. Variables are where information is stored, functions are pieces of code that can be executed and arrays are groups of


Learn pointers. Pointers are very important in C since you can directly access memory contents through pointers, unlike Java. The drawback to this is that if your program isn't thoroughly tested, it can crash.


Learn conditional statements, such as the "if" and "switch" statements. The "if" statement will be one of your most frequently used statements, you can execute code based on whether a condition is true or not (e.g. whether the color the user provided was red).


Learn loops. Learn the difference of the "for" loop and the "while" loop - make sure to avoid infinite loops! Learn the continue and break statements.


Learn data structures. Although data structures are not directly related to programming, but for an advanced user, knowledge of basic concepts in Computer Science is essential.


Start with small programs. When you are making your own code, try to identify the most essential part of the problem - is it the data input or the calling of the functions, the structure of the loop (these are some very elementary examples) and start from there. Then build upon that in small increments.











Tips


Remember, C is a programming language. Learning a programming language may not necessarily lead to learning to program, which is more about problem solving than about compiling and running a program in a specific language.


When encountering a syntax error when compiling, if you're stumped, search Google (or another search engine) with the error you received. Chances are someone has already experienced the same problem and posted a solution.


Find a good C programming book. A recommendable C resource book is "The C Programming Language" by Brian W. Kernighan, Dennis Ritchie (ISBN 0131103628). Find a book that has tutorials and projects to facilitate your exposure to C.

flower beds

C-programming l as a beginner i need help here. this is the question:?

Write a C program tha t p rint s the character s in a s t ring in rever se order.


char s[10] = "abcdefg";


char* cptr;


i can do without the pointers. which is simple but i need someone to use pointers!!!

C-programming l as a beginner i need help here. this is the question:?
try this:


#include "stdio.h"


#include "stdlib.h"


int main(){


printf("type a string:\n");


char* s = malloc(1);


int c = 0;


*s = getchar();


while(s[c] != '\n'){


c++;


s = realloc(s,c + 1);


s[c] = getchar();


}/*this gives a string, terminated by a newline*/


while(c != -1){


putchar(s[c]);


c--;


}


free(s);


}


but srsly, don't expect me or my fellow professionals to help you all the time!
Reply:Do you understand what the pointer is? My guess is that you are a little confused about that.





You probably have already learned that C does not have a variable to type string. One way to build a string is to use an array. In C, an array is a group of memory addresses that are next to each other (what is important is that the addresses are next to each other). Now, you don't know which memory addresses in your computer store this array. If you knew, you could go to the end of the array and print the value in the address. You would repeat this for the previous address, and so on until you got to the first address.





Like I said, YOU don't know where the array is stored, but your computer does. Use a pointer to look at (point to) the first element of the array. By incrementing the pointer, you look at the next memory address. So if you can find the end of the string (\0), you can decrement the pointer to look at the previous memory address.





Hope this makes sens.
Reply:Keep asking people to do your homework for you and you'll always fail in programming :P
Reply:Have you tried _anything_ yet?





int i = strlen(s);


char *cptr = %26amp;s[i - 1];





printf ("fwd: %s\n", s);


printf ("rev: ");


while(cptr %26gt;= s) {


printf("%c", *cptr--);


}


printf("\n");


Static cast in C++?

guys how can I use The static cast to write this C++ program:


Write a Program that prompts the user to input an integer between 0 and 35. If the number is less than or equal to 9, the program should output the number; otherwise, it should output A for 10, B for 11, C for 12, . . ., and Z for 35. (Hint: Use the cast operator, static_cast%26lt;char%26gt; ( ), for numbers%26gt;=10.

Static cast in C++?
The static_cast can be used to take a data type (like integer, float, etc) and cast it (aka convert it) to another data type like making an integer into a character like you need for this example.





The trick here is that the integer 35 isn't the ascii number for Z, so you will have to do a bit of addition before converting.





For example... if you look at an ascii chart you will notice that the capital "Z" is number 90.





static_cast%26lt;char%26gt;(90) will then give you the capital Z. So what we need to do is take the difference between 90 and 35... which is 55 and add it to every number the user types in greater than or equal to 10, then convert it.





So if the user entered.... 11, we would add 55 and get 66 then go static_cast%26lt;char%26gt;(66) to get a character "B". We then print out the character to screen.





As a side note, lower case letters start at 97 for "a" and go to 122 for "z" so that offset will need to be figured out if you want to use lower case.





I will let you figure that one out.





Hope this helps you out. Enjoy!
Reply:Please make few modifications to support your needs. The lines are broken.





To contact me mail me at m_gopi_m@yahoo.co.in.





I hope this is the program you are expecting.





//program for static casting.





#include%26lt;iostream.h%26gt;


#include%26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;





char static_cast(int);





void main()


{


int num;


char a;





clrscr();


cout%26lt;%26lt;"\n Enter a number: ";


cin%26gt;%26gt;num;





if(num%26gt;=0 %26amp;%26amp; num%26lt;=9)


{


cout%26lt;%26lt;"\n\n The given number: "%26lt;%26lt;num;


cout%26lt;%26lt;"\n\n The corresponding character: "%26lt;%26lt;num;


}


else if(num%26gt;9 %26amp;%26amp; num%26lt;36)


{


a=static_cast(num);


cout%26lt;%26lt;"\n\n The given number: "%26lt;%26lt;num;


cout%26lt;%26lt;"\n The corresponding character: "%26lt;%26lt;a;


}


else


cout%26lt;%26lt;"\n\n Cannot predict the value.";


getch();


}





char static_cast(int num)


{


int first='A'; //static casting is invoked here.


char a;


num-=10;


a=first+num;


return(a);


}


Need help with c- programming?

A few problems i need help with...


1. I have to have the user clear scores before entering the first set of test scores because the test score number starts of in the millions.


2. I can't get the program to enter a second set of numbers after the first set has been cleared.


3. How to get the program to count the sets as i enter them in. ( I will be saving them in a file)





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;math.h%26gt;














int main()


{





int eLoop=0,bsinp;


char menuResponse;


float score;


float average;


float x;


float max = 0;


float min = 1000;


float total = 0;


float sum;


int i = 0;


char buffer[BUFSIZ+1];


int scoresEntered;


int setsEntered;

















do{


/*Print the Menu*/





printf ( "\n\n\**********************************...


printf ("*****Test Score Statisics v2.0*****\n");


printf ("***********************************\n"...











printf ("[C] Clear Stats\n");


printf ("[E] Enter Test Scores\n");


printf ("[D] Display Test Score Stats\n");


printf ("[Q] Quit\n\n");


printf ("Type the letter of your selection and press %26lt;ENTER%26gt;\n");














gets(buffer);


menuResponse = buffer[0];





switch (menuResponse)


{


/*Clear all scores and tally the total sets*/





case 'C':


case 'c':


printf("All Scores Cleared.\n");


setsEntered++;


max = 0;


min = 100;


int i = 0;


float total = 0;





break;





case 'E':


case 'e':


while ( score ) {


printf("Please Enter test Score %d: ", i+1);


score = atoi(gets(buffer));


i = i + 1;


if (buffer[0] == 0) break;





if( score %26gt; max ) { /* Find Max Score*/


max = score;





}else{


if (score %26lt; min) { /* Find Min Score*/


min = score;


}


}


sum = score + sum; /* Find Sum Score*/


}





average = sum / (i-1) ; /* Find Average Score*/





break;





case 'D':


case 'd':


printf( "\n\nThe average score is %.1f\n", average);


printf( "%d Test Scores\n", i-1 );


printf( "Maximun Test Score = %.1f\n", max);


printf( "Minimum Test Score = %.1f\n", min);


printf( "\n\nPlease Clear Scores before preceding.");


break;





case 'Q':


case 'q':


eLoop=1;


break;





default:


printf("Please select a letter.\n");


break;





}











}while (eLoop!=1);





printf("Press Any Key.\n");


gets(bsinp);








return 0;


}

Need help with c- programming?
sorry I'll just have to paste the full code here (commented where necessary). there were a few other flaws as well, also added support for writing sets to file. enjoy.








#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;math.h%26gt;





int main()


{


int eLoop=0;


char menuResponse;


float score;


float average=0;


float max = 0;


float min = 0;


float sum=0;


int i = 0;


char buffer[BUFSIZ+1];


int setsEntered;


FILE *fd;





// open file where you put sets


if (NULL == (fd = fopen("mysets.txt", "w")))


{


printf ("\n Sorry couldn't open mysets.txt, change path or give permissions.\n");


exit(1);


}





do


{


/*Print the Menu*/





printf ( "\n\n***********************************...


printf ( "*****Test Score Statisics v2.0*****\n");


printf ( "***********************************\n")...





printf ("[C] Clear Stats\n");


printf ("[E] Enter Test Scores\n");


printf ("[D] Display Test Score Stats\n");


printf ("[Q] Quit\n\n");


printf ("Type the letter of your selection and press %26lt;ENTER%26gt;\n");





gets(buffer);


menuResponse = buffer[0];





switch (menuResponse)


{


/*Clear all scores and tally the total sets*/





case 'C':


case 'c':


printf("All Scores Cleared.\n");


max = 0;


min = 0;


i = 0;


sum = 0;


average = 0;





break;





case 'E':


case 'e':





if (0 != i)


{


printf (" %26lt;%26lt;%26lt; YOU MUST CLEAR PREVIOUS SCORES FIRST %26gt;%26gt;%26gt;\n\n");


break;


}





score = 1; // needed for "while (score)" to start off properly


setsEntered++;


fprintf (fd, "Values for scores Set # %d\n", setsEntered);





while ( score )


{


printf("Please Enter test Score %d: ", i+1);


score = atof(gets(buffer)); // atof instead of atoi - you really need float values not integers


if (buffer[0] == 0) break;





// initialize min score here (= first score)


if (0 == i) min = score;





if( score %26gt; max )


{ /* Find Max Score*/


max = score;


}


// "else" should not be here


if (score %26lt; min)


{ /* Find Min Score*/


min = score;


}





sum = score + sum; /* Find Sum Score*/


i++; // increment counter here





// write entry to file


fprintf (fd, " Score %d: %.1f\n", i, score);


}





average = sum/i; /* Find Average Score*/





// write statistics to file


fprintf(fd, "The average score is %.1f\n", average);


fprintf(fd, "Maximun Test Score = %.1f\n", max);


fprintf(fd, "Minimum Test Score = %.1f\n", min);


fprintf(fd, "---------------------------------------...





break;





case 'D':


case 'd':


printf( "\n\nThe average score is %.1f\n", average);


printf( "%d Test Scores\n", i );


printf( "Maximun Test Score = %.1f\n", max);


printf( "Minimum Test Score = %.1f\n", min);


printf( "\n\nPlease Clear Scores before preceding.");


break;





case 'Q':


case 'q':


eLoop=1;


break;





default:


printf("Please select a letter.\n");


break;





}


} while (eLoop!=1);





// close file


fclose (fd);





printf("Press Any Key.\n");


gets(buffer);





return 0;


}
Reply:You need to initialise


int setsEntered=0


float average = 0; (This is incase you do 'D' before entering any scores!


float min = 0; and add a check in the while loop


if ((min == 0) || (score %26lt; min)) { /* Find Min Score*/


min = score;


}





scoresEntered is not used


You are defining total within the case block but it is NOT used.





Initialise the values before the while loop after the case 'e' so you don't have to manually clear them each time before entering a set of scores.





sum = 0;


min = 0;


max = 0;


i = 0;





Increment the setsEntered when you actually enter the sets


case 'e':


setsEntered++;


while (score) {





You need to change the while (score) to a


do {


}while(score);


As at the end for the first set score is set to 0 so it never enters the while loop again.





I think that is it.


Game Idea C++ help with map?

I have a plan to create a simple interactive video game with c++. The game will have no graphics except ASCII characters. I wanted to initialize a map and have mountains return a char value of '^', grass a char value of '.'. The character will be a '@'.





I've only been studying the basic syntax of c++ and have yet to get into the actual implementation of this syntax to create something worthwhile and enjoyable.





My problem however is defining a map, and when defining the map how will the character move within it. How can I create a map that will define an x and y environment in which if my character presses 'w' on the keyboard he'll move north or y+1. Have 'a' move me x - 1 and etc.





Should I use a structure? A multi-dimensional array? If you answer could you please give me some detailed instructions as well. And as always any help would be greatly appreciated. Thanks. :)

Game Idea C++ help with map?
I would use a 2D array, and make the number of columns and rows configurable, like this:








class Map


{


private:


char* map;


int numCols, numRows;


int charPositionX, charPositionY;





public:


Map(int columns, int rows) : numCols(columns), numRows(rows), charPositionX(0), charPositionY(0)


{


map = new char[rows][columns];


}





void setCharPos(int x, int y)


{


// do some bounds checking


charPositionX = x;


charPositionY = y;


}





char getMapChar(int x, int y)


{


// do some bounds checking


return map[y * numRows + x];


}





void getMapRow(int y, char* rowOut)


{


// do some bounds checking, and null checking


// or use a std::string reference here to avoid


// buffer overruns


memcpy(rowOut, map[y * numRows], numCols);


}





void moveCharUp()


{


if (charPositionX %26gt; 0)


charPositionX--;


}





void moveCharDown()


{


if (charPositionX %26lt; (numRows - 1))


charPositionX++;


}





//and so forth





};
Reply:for this you would use a Multi dimentional array...


Depending on how you want to code it you can use that to define the landscape. This could be a predefinded landscape or one generated at runtime....





then as the object moves accross you can use its coordinates with the landscape'd data for that position and perform the nessesary function...

wedding flowers

I need some help in C++ to get this code compiled?

#include %26lt;iostream%26gt;





#include %26lt;cstdlib%26gt;


#include %26lt;ctime%26gt;


using namespace std;











int random_1();











int main()











{





int i = 0;





int j = 0;





int check;





int check_1;





char play_again = '\n' ;











int tortoise[70];





int hare[70];











cout %26lt;%26lt; "BANG !!!!!" %26lt;%26lt; endl;





cout %26lt;%26lt; "AND THEY'RE OFF !!!!!" %26lt;%26lt; endl;

















while(play_again == '\n')





{











while(i %26lt;= 69 %26amp;%26amp; j %26lt;= 69)





{











tortoise[i] = 0;;





check = random_1();











if(check == 1 || check == 2 || check == 3 || check == 4 || check ==


5)





tortoise[i+=3] = 0;











if(check == 6 || check == 7)





tortoise[i-=6] = 0;











if(check == 8 || check == 9 || check == 10)





tortoise[i+=1] = 0;











char *ptr;





char line[71] = "---------------------------------------...











ptr = line;











if(i %26lt; 0){





i = 0;





*(ptr + i) = 'T';}











*(ptr + i) = 'T';











hare[j] = 0;





check_1 = random_1();











if(check_1 == 1 || check_1 == 2)





hare[j] = 0;











if(check_1 == 3 || check_1 == 4)





hare[j+=9] = 0;











if(check_1 == 5)





hare[j+=12] = 0;











if(check_1 == 6 || check_1 == 7 || check_1 == 8)





hare[j++] = 0;











if(check_1 == 9 || check_1 == 10)





hare[j-=2] = 0;











if(j %26lt; 0){





j = 0;





*(ptr + j) = 'H';}











*(ptr + j) = 'H';











if(i == j){





*(ptr + i) = 'O';





*(ptr + i + 1) = 'U';





*(ptr + i + 2) = 'C';





*(ptr + i + 3) = 'H';}











cout %26lt;%26lt; "%s\n\n" %26lt;%26lt; endl;











break;











}

















if(i %26gt;= 69)





{





cout %26lt;%26lt; "TORTOISE WINS!!! YAY!!!" %26lt;%26lt; endl;





break;





}











if(j %26gt;= 69)





{





cout %26lt;%26lt; "HARE WINS. YUCH." %26lt;%26lt; endl;





break;





}











if(j %26gt;= 69 %26amp;%26amp; i %26gt;= 69)





{





cout %26lt;%26lt; "IT'S A TIE" %26lt;%26lt; endl;





break;





}











cout %26lt;%26lt; "Press enter" %26lt;%26lt; endl;





cin %26gt;%26gt; "%c",%26gt;%26gt; %26amp;play_again); // Error Here











}











return 0;

















}





int random_1()











{





srand(time(NULL));





return (1 + rand() % 10);





}

I need some help in C++ to get this code compiled?
Change the problem line to this:





cin %26gt;%26gt; play_again;
Reply:Iam studing 11-12th now.


so iam studying now about c++.


i wiil ans later.


sorry
Reply:would be better if you tell us the compile error you're receiving.
Reply:The previous answer was correct in the fix for your cin syntax, but this isn't going to do what you want. The newline won't be stored in play_again. Test your code, and you'll see how it works, or doesn't.





Something like this will do the job for you:





string s;


while (s.length() == 0) {


// ...


cout %26lt;%26lt; "Press return to continue, or x to exit ... ";


getline(cin,s);


}


Question on c I am using linux/unix to write my code?

This is an external function from a big program i am doing a stub test because if i run the whole program the questions overload and i cannot input data the only variable that i can input is the lastname. This is what the warning say employedata.c:7: warning: incompatible implicit declaration of built-in function


employedata.c:8: warning: incompatible implicit declaration of built-in function


#include %26lt;string.h%26gt;


#define MAX 5


void employedata(char lastname[30+1],char firstname[30+1],


float *hours,float *payrate,float *ssidefr)


{


int i = 0;


printf("Enter employee last name ");


scanf("%s", lastname[i]);


printf("Enter employee first name ");


scanf("%s", firstname[i]);


printf("Input employee hours ");


scanf("%f", hours[i]);


printf("Input employee payrate ");


scanf("%f", payrate[i]);


printf("Input deferred earnings ");


scanf("%f", ssidefr[i]);


}

Question on c I am using linux/unix to write my code?
It can't find the printf function. Add:





#include %26lt;stdio.h%26gt;
Reply:What exactly is the question ?





If you are wondering why you are getting warnings, add this in the beginning:





#include %26lt;stdio.h%26gt;
Reply:i think scanf expects a pointer, but you give him a char.





try this:


scanf("%s", %26amp;lastname[i]);


scanf("%s", %26amp;firstname[i]);

paid survey

I need help with pointers in C++?

Write a function that takes a C string as an input parameter and reverses the string. The function


should use two pointers, 'front' and 'rear'. The 'front' pointer should initially reference the first


character in the string, and the 'rear' pointer should initially reference the last character in the


string. Reverse the string by swapping the characters referenced by 'front' and 'rear', then increment


front to point to the preceding character, and so on, until the entire string is reversed. Write a


main program to test your function on various strings of both even and odd length.


*/


#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using namespace std;





void swap_char(int* pFront, int* pRear);





int main(){


string sentence;


int *pFront, *pRear;


cout %26lt;%26lt; "Type in a sentence of less than 40 characers: \n";


cin %26gt;%26gt; sentence;


swap_char(pFront, pRear);


return 0;


}


void swap_char(int* pFront, int* pRear){


while(pRear %26gt; pFront)


{


string sentence;


char temp;


%26amp;temp =

I need help with pointers in C++?
Some tips:





pFront and pRear should be char*, not int*.





You need to set pFront and pRear to something before calling swap_char. However, the problem statement says swap_char's argument should be a "C string". I assume it wants you to use character array, and not a C++ string object. Inconvenient as that may be, you need this signature:





void swap_char(char * const s);





(i.e., const pointer, non-const data)





You might think you should have this call in main() :


swap_char(sentence.c_str());





That won't work, though, because c_str() returns a const char*, and swap_char needs to modify the character array. You need to declare a character array, then copy the c_str from sentence. Also, there's no need to limit the input to 40 characters, or any length.





So you need something like this:





getline(cin,sentence);


char *line = new char[sentence.length()+1];


memcpy(line,sentence.c_str(),sentence....


swap_char(line);





Why getline instead of cin's operator%26gt;%26gt;, you ask? Try them both, you'll see.





Also, #include %26lt;cstring%26gt; for memcpy. And when you're done, don't forget to: delete [ ] line;





I'll leave the guts of swap_char for you to work out, but this should get you going in the right direction.


Need help with io in C++, have read much programmed little?

I am somewhat familiar with input/output in programming, but am having problems using file io in C++. This is my skeleton type program:





#include %26lt;stdio.h%26gt;


#include %26lt;fstream.h%26gt;


int main(int argc, char *argv[])


{ ifstream filein; ofstream fileout; char ch;


filein.open("input.txt", ios::in);


fileout.open("output.txt", ios::out);


for(filein.get(ch); ch!=EOF; filein.get(ch));


{


fileout.put(ch);


}


filein.close();


fileout.close();


return 0;


}





i created a text file input.txt and output.txt, input has "asd" in it and output is empty, i want it to write the asd to output.txt





using EOF it is infinite loop, and using NULL it terminates doing nothing, I have read a lot about c/c++ but this is my first stab at programming in it and it is taking me forever to get all syntax and small stuff takin care of. Please tell me what I am doing wrong. Thank you :)

Need help with io in C++, have read much programmed little?
http://www.cplusplus.com/doc/tutorial/fi...





Please get a better book. The above code is terrible. And outdated.





Just open up two filestreams and transfer one line to another. Use getline to take in entire lines. Store them in strings. As in %26lt;string%26gt; strings.





EDIT: I'll give you the code. Please get a newer book so you understand what I did.





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;


using namespace std;





int main()


{


string str;


ifstream infile("input.txt");


ofstream outfile("output.txt");


if (infile.is_open())


{


while (!infile.eof() )


{


getline(infile, str);


outfile %26lt;%26lt; str %26lt;%26lt; endl;


}


infile.close();


outfile.close();


}





else cout %26lt;%26lt; "Unable to open file";





return 0;


}
Reply:use ifstream::in and ifstream::out instead!


C++ - what's the default method of opening a file passed to main via *argv[]?

I'm a self-taught C++ programmer, and I stumbled across the second method of main(), being main(int argc, char *argv[]) of course.





The first thing I did was create a small sample program that simply displayed the value of argc and all the values of argv[] that were passed to it. After experimenting with it a bit, I noticed that argv[0] is always the command line text used to execute my program, and the other argv values contain everything else that was passed to it. My question is, where can I go to learn more about the standard methods of passing programs arguments?





I was interested about learning the following in particular:





-How are parameters starting with tags such as -o, -f, -a, and so on usually handled?





-I noticed that, if a file opens the program via a file extension associan, argv[1] contains the location of the file calling my program. How am I to know when argv[1] is a file location, and not a usual parameter? Should I check for C:\? I've just been checking for "*:\"

C++ - what's the default method of opening a file passed to main via *argv[]?
The truth of the matter is that C++ doesn't do any handling of files/flags/parameters whatsoever. When you pass extra command lines to a program, the strings themselves are passed as char arrays (char []) sequentially into the elements of argv[] (an array of char arrays). When a space occurs in the command line, that serves as a delimiter, so every time a space show up, a new char array is added to argv[] and argc is incremented. The one exception to this delimiter rule is when you use quotes on the command line. A quoted string is passed in its entirety as a single argv element. Thus, if you ran MyProgram.exe -o -f -a C:\Program Files\MyProgram\Program Data\test.dat then argv will be an array of size argc containing the following char arrays:


argv[0] = MyProgram.exe


argv[1] = -o


argv[2] = -f


argv[3] = -a


argv[4] = C:\Program


argv[5] = Files\MyProgram\Program


argv[6] = Data\test.dat


making argc=7. Thus if you wanted to retrieve the original command line, you could do something like the following:


string argument="";


for(int i=0; i%26lt;argc; i++)


{


argument+=argv[i];


if(i!=argc-1) //add spaces to all but the last element


argument+=" ";


}


which will result in argument containing exactly what was placed on the command line. Notice how the path argument was split into multiple char arrays because of the spaces in the path. This is sometimes a big problem if not handled correctly. You will have to decide how your program will need to parse argv[] depending on expected input and how you plan on handling it. Notice also that argc contains one more than the number of command line arguments (because argv[0] is the program name itself, useful sometimes when you want to title a window or change your output like in a help printout of how to use the program depending on the name of the exe itself, meaning if the user renames the file it will still show the proper command line to use!). You have to be careful to check argc before you try parsing the command line though or you'll get out of bounds errors, leading to your program crashing or using invalid data at best, taking down other programs or even the OS at worst, though you'll need an older OS to make those happen really). Once you have properly parsed your command line and have gotten the string "C:\\Program Files\\MyProgram\\Program Data\\test.dat" finally, you can use your favorite method for opening files from path, ranging from C's FILE pointer to more complex methods in C++, MFC, Win32, ATL, or your own self-written file class. Have fun!


How do i write a c++ program that reads the top line of a text tile till the newline charecter?

I need to write a c++ program, that reads the top line of a txt file stopping at the end of the line.





i tried:





#include %26lt;iostream.h%26gt;


#include %26lt;fstream.h%26gt;


#include %26lt;stdio.h%26gt;





void main()


{


int i;


char l[20];


char tem='0';


ifstream example("d:\\test2.txt");





for(i=0; tem!=char(10) %26amp;%26amp; !example.eof();i++)


{


example%26gt;%26gt;tem;





if(tem!=char(10))


{


l[i] = tem;


}


}





for(i=0; i%26lt;6; i++)


{


cout%26lt;%26lt;l[i];


}


cout%26lt;%26lt;endl;





}





But the result is just 123456 even though my file says:


"123





456"





What am i doing wrong/ what should i do?

How do i write a c++ program that reads the top line of a text tile till the newline charecter?
The bug is the line:





example%26gt;%26gt;tem;





The "%26gt;%26gt;" operator seems to ignore the newlines so, do this instead:





tem = example.get();





But the code can be greatly simplified once you think about how C++ (but not C) can deal with lines as whole strings instead of as arrays of characters. Also, C++ has standard methods in string/fstream that can read files line-by-line. These two realizations result in this simplified version of what you're trying to do:





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;





using namespace std;





int main ()


{


    ifstream file("test2.txt");





    // see http://cppreference.com/cppstring/getlin...


    string line;


    getline( file, line);


    cout %26lt;%26lt; line;





    file.close();


}








Since you're learning, a few nick picks about your code if you don't mind:





1) "void main()" is not standard C++, use "int main()" instead, according to the creator of C++:


http://www.research.att.com/~bs/bs_faq2....





2) stdio.h is C, not C++. stdio.h lets you do C-style printf's (among other things) instead of cout %26lt;%26lt; (which is provided by iostream) so you don't need to include stdio.h here.





3) Putting a ".h" at the end of the iostream and fstream includes (I believe?) uses the deprecated versions of those libraries. You're better off omitting the ".h" Unless you're using old compiler/libraries that don't have the newer versions.
Reply:try using


'\n' instead of char(10)


or just 10








anyways if you're in windows and you made your file with notepad (and others..) your new lines would be made of two caracters carriage return and line feed \r\n, so your l would have an extra \r inside.

customer survey

C++ class error, it does not make sense to me at all!?

The code is below... When I convert to letter then number the binary is right. When I convert the number then letter the binary messes up. Help me.





class menu


{


public:


void convert (int input);


int getValue (int input);


};








int a[8],k=1,i ;


void menu::convert(int input)


{





int d = input;


i = 0;


while (d!=0)


{


a[i]=d % 2;


d/=2;


i++;


}


cout %26lt;%26lt; "The binary code of the given number is :";


for(i=7;i%26gt;=0;i--)


cout %26lt;%26lt; a[i] ;


cout %26lt;%26lt; endl;


}


int menu::getValue(int i)


{


char ans;


int ans2;


cout %26lt;%26lt; "What letter/number?\n%26gt;%26gt;";


if (i == 2){


cin %26gt;%26gt; ans;


ans2 = int (ans);}


else{


cin %26gt;%26gt; ans2;}


return ans2;


}


int main()


{


for (;;)


{


menu user ;


int c =0, d =0;


cin %26gt;%26gt; c;


if (c %26lt;= 2)


{ d = user.getValue(c);


user.convert(d); }


else{


break;}


}


system("pause");


return 0;


}

C++ class error, it does not make sense to me at all!?
Your convert() function has few bugs.