PDA

View Full Version : Help with extremely basic C++


gvatar
12-10-2007, 04:59 PM
Im a newbie in C++ having started learning it for only a few days, so pardon me for any misconceptions I may have or my ignorance.

For some queer reason, the following code does not produce the desired effect of allowing the user to input ten different words and displaying the fifth word. Instead, it allows an infinite input that does not terminate with either \n or \t. Oh, any suggestions to shorten the code would be appreciated :thumbsup:

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

int main()
{
string str1, str2, str3, str4, str5, str6, str7, str8, str9, str10;

cout << "Enter the phrase:" << endl;
getline(cin, str1, '\t');
getline(cin, str2, '\t');
getline(cin, str3, '\t');
getline(cin, str4, '\t');
getline(cin, str5, '\t');
getline(cin, str6, '\t');
getline(cin, str7, '\t');
getline(cin, str8, '\t');
getline(cin, str9, '\t');
getline(cin, str10);
cout << str5;
system("pause");
return 0;
}

brad211987
12-10-2007, 05:15 PM
Try taking the third parameter off of the rest of your getline statements so they all look like number 10. The getline defaults to a '\n' delimiter which should make each getline stop reading input when the user presses enter.

gvatar
12-10-2007, 05:21 PM
Thanks for the advise :), it stopped the infinite input problem. However, is there not a way to make '\t' the delimiter as I want to input individual words and not strings.

brad211987
12-10-2007, 05:57 PM
Were you using the tab key between your words when you tested before?

gvatar
12-10-2007, 06:05 PM
http://img513.imageshack.us/img513/8349/tabma1.th.jpg (http://img513.imageshack.us/my.php?image=tabma1.jpg)

Is this what you meant by tab key between the words?
If it is... as you can see, after the 10th word it continues receiving input instead of showing the 5th word.

brad211987
12-10-2007, 06:21 PM
In your original code, you don't specify a delimiter for the 10th one, maybe you should try it with all of them using '\t' as the delimiter.

gvatar
12-10-2007, 06:28 PM
The result is the same... But I've just realised my stupidity, I could've just made " " the delimiter. Thanks anyway +Rep :)

-Edit : I tried and it seems " " can't work...

oracleguy
12-12-2007, 04:39 AM
If you don't care about words having spaces, you can easily use space as the delimiter if you do:

cin >> str1 >> str2 >> str3 >> str4 >> str5 >> str6 >> str7 >> str8 >> str9 >> str10

gvatar
12-12-2007, 07:23 AM
It worked! Thanks alot :thumbsup: