@degausser
To me, the "word for word" instructions don't are quite match up with the examples you provide. Were they provided with the instructions, or are they your interpretation?
Taking the instruction as literally as possible,
1 2 3 4 5 6
|
Allow the user to enter characters
until the following requirements have been met:
1. Read a single non-whitepsace character
2. Read 5 space characters
3. Read a single non-whitepsace character
4. Output these 7 characters to the user
|
It sounds like you are looking for a run of 5 spaces and will then display the chars either side of it.
But step 2 would need to read something like "read chars until you pass 5 spaces" to handle strings like "1 3444 a".
Going with the new step 2, the following code sort of handles single lines which start with a non-space, like "1 3444 a", where the 'last char' displayed is the first non-space after 5 spaces have passed by.
(This isn't what your orig. post wanted. To display "1 c" rather than "1 a" for an input of "1 3444 a", you need to keep track of the last char and then terminate the loop when you get the 6th space (but not display it), rather than terminating the loop when you get the first non-space char after the 5th space.)
For example:
Enter a string with a total of 5 embedded spaces
1 3444 a
1 a |
Enter a string with a total of 5 embedded spaces
1 2 3 4 5 6 7 8 9
1 6 |
Enter a string with a total of 5 embedded spaces
1 21 321 4321 54321 654321
1 6 |
Or even
Enter a string with a total of 5 embedded spaces
Enter a string with a total of 5 embedded spaces
E t |
but has trouble with multi-line strings as the o/p occurs at the same time as the i/p procressing
Enter a string with a total of 5 embedded spaces
bcsa a
b
d
c
c |
To fix this you'd need to defer the o/p until the the whole of the i/p is processed.
This code also get confused by leading spaces.
But it does handle too many spaces.
Enter a string with a total of 5 embedded spaces (here there are 3 spaces between each 3)
3 3 3
3 Error! |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
using namespace std;
enum {
want_more = -1,
found_match = 0,
error_occured = 1
};
int main() {
int ret = want_more;
cout << "Enter a string with a total of 5 embedded spaces " << endl;
cout << endl;
size_t space_count = 0;
char in = '\0';
cin.get(in);
cout << in;
while(ret == want_more){
if(' ' == in) {
if(5 > space_count) {
cout << in;
++space_count;
} else {
ret = error_occured;
}
} else {
if(5 == space_count) {
ret = found_match;
cout << in;
}
}
cin.get(in);
}
if(ret != found_match) {
cout << "Error!" << endl;
}
cout << endl;
return ret;
}
|