getline

closed account (DGURE3v7)
hey guys so im trying to have a user enter a word and it finds the anagram and as long as the user keeps entering the word it keeps finding the anagram but when the user hits enter the program stops. for some reason after hitting enter my program does to a new empty line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main(){
    hw h;
    string a;
    while(true){
        cout<<"enter a word(press space to exit): ";
        cin>>a;
        if(a=="\n"){
            cin.ignore();
            break;
        }
        cout<<"anagrams of "<<a<<" is ";
        h.display(a);
    }
    return 0;
}
The >> operator ignores all spaces and newlines, so it's no use comparing the result with say "\n".

Use this to read a whole line.
https://www.cplusplus.com/reference/string/string/getline/
If the user just pressed enter, you have an empty line as a result.
closed account (DGURE3v7)
i still dont understand? i set line 7 to be if(a==" ") and line 6 to be getline(cin,a) but when ever i press enter the code will just display
enter a word(press enter to exit): dog
anagrams of dog is dog
enter a word(press enter to exit): cat
anagrams of cat is cat
enter a word(press enter to exit): apple
anagrams of apple is try another word
enter a word(press enter to exit):
anagrams of is try another word
enter a word(press enter to exit):
anagrams of is try another word
enter a word(press enter to exit):
anagrams of is try another word
enter a word(press enter to exit):
Salem is saying that by pressing enter you are not assigning "\n" to the string so checking for it does nothing. Perhaps you should just check for an empty string?
if(!a.size())
" " is not an empty string. It's a string consisting of a single space.
You need to compare to "", or use a.size() == 0 (as goggles gabbled).
1
2
3
4
5
6
7
8
9
int main()
{
	hw h;

	for (string a; cout << "enter a word (press enter to exit):" && getline(cin, a) && !a.empty(); ) {
		cout << "anagrams of " << a << " is ";
		h.display(a);
	}
}

Last edited on
Topic archived. No new replies allowed.