While loop help?

I'm trying to create a program that reads a text character by character.
I'm also trying to make it display every variable before the equal ("=") sign.
But it is not working...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
using namespace std;

int main()
{
	const int MAX = 10;
	char charArray[MAX];

	cout << "Enter a 10 letter text: " << endl;
	while ((cin.getline(charArray, 10, '\n')) != "=")
	{
		cout << charArray << endl;
		break;
	}
	system("pause");
	return 0;
}
Youre thinking about the arguments of while() wrong. You're checking the return value of cin.getline() which is likely a bool ( correct me if I'm wrong there ) against a character value. You should perform the read inside the while loop and check what you read right after to see if there were any = involved. Maybe use a bool for the loop and set it on/off depending on what got read into your buffer. Hope that helped let me know if I need to be more specific.

Btw I would write some code for you but I'm using my phone and this keyboard sux for that
Last edited on
I think the cin.getline () function is part of the C std Library.
For string s;
It may be easier to use (C++) getline(cin,s).
If you typed in jebasqrlisge then s would hold this string
You could get the length of the string with s.length().
If s is equal to jebasqrlisge then s[2]='b'.
cin.getline() returns an std::istream&. I think you maybe wanted something else... :)
http://www.cplusplus.com/reference/iostream/istream/getline/

Also, why not use C++ strings, as buffbill suggested? This way, you can bypass the maximum size issue. You'd probably be better off using std::getline() with those, though be aware that they also return std::istream&s!
http://www.cplusplus.com/reference/string/getline/

Finally... you'll probably want a loop that's extremely different. Getline gets exactly what it says it does on the tin, rather than single characters. You can still use it, but I'd suggest moving it before the loop, and then iterating over the individual characters, checking and printing each one.

Alternatively, I would also suggest using a string's find and substr functions and eliminating the loop altogether. ;)
http://www.cplusplus.com/reference/string/string/find/
http://www.cplusplus.com/reference/string/string/substr/

Happy coding!

-Albatross


EDIT7: I think I'm done editing...
Last edited on
inside the loop do a memset(charArray,'\0',sizeof(charArray));

delete the array and re use it. Its just a better way.
I agree with the above, using strings would be much safer. Also find/substring would be a great way to parse the input. Sorry if I missled you OP!
Topic archived. No new replies allowed.