[c++] kiedy i jak sprawdzić eof() podczas czytania z cin

0

Witam. Mam problem ze zrobieniem petli while, gdzie warunkiem dzialania jest niebycie eof'em. Nie umiem tylko tego zapisac... Dostaje błąd kompilacji:

error C2228: left of '.eof' must have class/struct/union

nie wiem jak to zrobic ;[

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

int main()
{
	string wejscie;
	while(!cin(wejscie).eof())   // nie dziala
	{
		cin >> wejscie;
		string s(wejscie.begin(),wejscie.end());
		string::iterator pos;
		reverse (s.begin(), s.end());
		cout << s << endl;
	}
}

0

ok jestem durniem ... nie wiem po co chcialem zeby cin byl zmienna :P popawiony dzilajacy kod:

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

int main()
{
	string wejscie;
	while(!cin.eof())
	{
		cin >> wejscie;
		string s(wejscie.begin(),wejscie.end());
		string::iterator pos;
		reverse (s.begin(), s.end());
		cout << s << endl;
	}
}
0

hmmmm a jednak nie dziala... kiedy pojawia sie EOF program wypisuje jeszcze raz ostatni odwrocony string.... ktos wie czemu ?

0

to sprawdź, czy EOF nie pojawił się PO odczycie:

if( (cin >> wejscie).eof() ) break;
0
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
	string wejscie;
	while(!(cin >> wejscie).eof())
	{
		string s(wejscie.begin(),wejscie.end());
		reverse (s.begin(), s.end());
		cout << s << endl;
	}
}

Ok zrobiłem tak. niby dziala... ale durny spoj caly czas mi to odrzuca... nie wiem juz co tu jest zle

0

Można też tak

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

int main()
{
        string wejscie;
        while(cin >> wejscie)
        {
                string s(wejscie.begin(),wejscie.end());
                reverse (s.begin(), s.end());
                cout << s << endl;
        }
}

Pamiętaj, że będą wczytywane pojedyncze słowa, a nie całe linie (nie wiem jakie zadanie ze spoja robisz).

BTW. nie rozumiem po co kopiujesz wjescie do s. W szczególności możesz napisać tak:
s = wejscie;
zamiast kopiowania przez konstruktor.

Po drugie w ogóle nie ma potrzeby kopiowania. Zamiast na s operujesz na wejscie i po sprawie.

0
        string wejscie;
        while(cin >> wejscie)
        {
                string s(wejscie.rbegin(),wejscie.rend());
                cout << s << endl;
        }

lub bespośrednio bez tworzenia kopii łańcucha:

        string wejscie;
        while(cin >> wejscie)
        {
                copy(wejscie.rbegin(), wejscie.rend(), ostream_iterator<char>(cout));
                cout << endl;
        }

1 użytkowników online, w tym zalogowanych: 0, gości: 1