By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,655 Members | 1,005 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,655 IT Pros & Developers. It's quick & easy.

Homework Help

P: 7
Hi, I'm a new user of this webside and also a begginer of C++. Hopefully can get somehelp from you guys. :)

Now I meet some problems, anybody can help me with the coding?

Requirement: Write a simple C++ program using cin and cout. The program will read from cin, cout the number of words read, until the end of file(eof). Then display the last word together with the number of words read.

Sample Input:

I am a fresh man here
Please kindly help me 1,2,3

Sample Output:

last word: 1,2,3
Word count: 11

Friends, hopefully can get your reply before 31, Sep... :D

Thanks a lot.
Aug 29 '06 #1
Share this Question
Share on Google+
7 Replies


Expert Mod 100+
P: 2,328
Hi GAOZH,

Our policy on the site for homework help is that you must attempt to the problem first yourself. If you run into problems we can help you debug your code.

KUB
Aug 29 '06 #2

P: 7
I worte a simple code below for the above mentionned requirements. Can tell me in what condition the program can not satisfy the requirements? :)

#include <iostream>
#include <string>
using namespace std;

int main()
{
string firstWord, lastWord;
int count = 0;

cin >> firstWord; // Get the first word
lastWord = firstWord;

while(!cin.eof()) // Check whether is end of file
{
cin >> lastWord; // Get the last word
count++;
}

cout << firstWord << " " << lastWord << " " << count << endl;
system("pause");

return 0;
}//end main
Aug 31 '06 #3

Banfa
Expert Mod 5K+
P: 8,916
This doesn't work because cin.eof() is never true, i.e. you never get to the end of the input stream
Aug 31 '06 #4

P: 7
End of input stream can be done by press Ctrl + z. I compile and run the above code and got all the output correct (Which I think so... : ) ). Then I changed the while loop from " while (!cin.eof()) " to "while (cin)", I got the same output. Is there any differences between the two while loops? ^_^
Aug 31 '06 #5

Banfa
Expert Mod 5K+
P: 8,916
I tried Ctrl + Z and it didn't work, which isn't to say it does't work for you.

Logically the stdin never ends.
Aug 31 '06 #6

P: 7
Try after typing the words you want, press Enter first, then Ctrl + z, then, Enter again to show the results.
Sep 4 '06 #7

Banfa
Expert Mod 5K+
P: 8,916
Try after typing the words you want, press Enter first, then Ctrl + z, then, Enter again to show the results.
That is not intuitive and I would be surprised if you lost marks because of it (or found that like me your professor/teacher thinks the program does not work because you can't end the input stream).
Sep 4 '06 #8

Post your reply

Sign in to post your reply or Sign up for a free account.