![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Feb 2005
Posts: 9
Rep Power: 0
![]() |
Need Help Understanding
Hi.
I have this assignment for programming in which I have to write an encoding program. The program has to ask the user how many phrases they want to encode, and then take a phrase, encode it, take another phrase, encode it, etc. The encoding process works like this: a value of 0 is added to the first character in the line, a value of 1 is added to the second character in the line, a value of 2 is added to the third character in the line, and so on. Here is the code: #include <iostream.h>
#include <string>
//Function Prototypes
void encode (char *string, int& stringlen);
void print (char *string1);
int main(void)
{
int amt_phrase, cnt, phrlen;
const int SIZE = 120;
char phrase[SIZE];
cout << endl;
cout << "How many phrases would you like to encode? ";
cin >> amt_phrase;
cout << endl;
//for loop runs for the amount of phrases the user wants to encode
for (cnt=0; cnt <= amt_phrase; cnt++)
{
cout << "Enter the phrase to be encoded. ";
cin.getline (phrase, SIZE);
phrlen = strlen(phrase);
encode (phrase, phrlen);
print (phrase);
}
return 1;
}
//Function takes the phrase and encodes it
void encode (char *string, int& phraselen)
{
int y = 0;
for (int cnt1=0; cnt1 <= phraselen-1; cnt1++)
{
y = (int(string[cnt1]) + cnt1);
string[cnt1] = char(y);
}
}
//Function prints out encoded phrase
void print (char *string1)
{
cout << "Encoded: " << string1;
cout << endl;
cout << endl;
}I have the program working correctly, except I do not understand why it is doing one thing. After the program asks the user to input how many phrases they want to encode and the user hit return, the program outputs on one line "Enter the phrase to be encoded. Encoded: " The program then proceeds to do what it is suppose to. A sample of the output is below. (Program Start) How many phrases would you like to encode? 1 Enter the phrase to be encoded. Encoded: <-- Output in question Enter the phrase to be encoded. blue sky Encoded: bmwh$xqC (Program End) I'm not sure why it is doing this and if someone could explain to me why it is doing this, it would be greatly appreciated. Thanks. |
|
|
|
|
|
#2 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
You'll need to flush the input buffer before you read in any more, to stop the characters that weren't read (such as a newline) from being read the next time round. Eggbert wrote a simple function that does this:
void iflush (FILE *in)
{
int ch;
while ((ch = fgetc (in)) != EOF && ch != '\n');
} |
|
|
|
|
|
#3 |
|
Newbie
Join Date: Feb 2005
Posts: 9
Rep Power: 0
![]() |
Ok, I'll get right on that.
Thanks for the help. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|