cin doesn't append a \n
It should append a \0 though - try testing for that in your loop
cin doesn't append a \n
It should append a \0 though - try testing for that in your loop
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Hehe, I knew that. What a dumb mistake. Thanks for the help again
Can I lock this thread, btw?
I have a new question. How do I clear s1 after every loop?
Here is my code as it looks now. Apparently cin.clear() doesn't work, or I'm using it wrong.
Code:char s1[100]; int n=0, t=0, x=0; while(x==0) { cout << "Inset text: "; cin >> s1; while(s1[n]!='\0') { t++; n++; } cout << "You text has " << t << " characters in it\n"; cin.clear(); }
Last edited by stillwell; 10-07-2004 at 08:08 AM.
Clear s1?? Like erasing the string??
perhaps s[0]=0; ?
No, like getting rid of the input just made.
i.e I type in wolla and s1 gets the value wolla. If I then input the word, word, 2nd time around, s1 will be worda, and still give the output 5, even thou word is a 4 letter word.
How do I clear s1, so that there will be no data in it, when I loop.
Last edited by stillwell; 10-07-2004 at 08:08 AM.
I wish I understood why people think C-style strings are easier for newbies to work with...Code:#include <string> using namespace std; //... string foo; cin >>foo; //or getline(cin, foo) for \n terminated cout <<foo.size();
Ah, that's the same program, but with string? How would I clear the string then?
I also still want to know how to clear the char array s1.
Last edited by stillwell; 10-07-2004 at 08:35 AM.
Originally Posted by stillwellYou would not need to clear the contents if using a string... the cin or getline calls will overwrite any existing contents of the string container.Code:string foo; ... foo.erase(); // Clears contents of string
If you want to stick with a character array, you can probably do something like calling memset on your array to 'zero' it out every time within your loop:Originally Posted by stillwell
Code:char array[100]; ... memset(array,0,sizeof(array));
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
Doesn't seem to work. Isn't it supposed to be written like so, in my program?
Do I need to include some stream?Code:memset(s1,0,sizeof(s1));
(sorry if I'm not using correct termanalogy, but I'm a damn noob )
"[EDIT]: Wow, you guys are fast today..."
Hehe, no kidding. I didn't even see the 2 other answers.
Last edited by stillwell; 10-07-2004 at 08:42 AM.