Hi, I'm working on a function here and I'm trying to make the loop end if a '.' is ever entered. But I need it to process input up until the '.' and ignore anything after the '.' on the same line of input. The input loop should end after the user presses enter if a '.' was entered on a line.
1 2 3 4 5 6 7 8 9 10
void getInput(char input[])
{
constint size = 9999;
int index = 0;
cout << "Enter a sequence of characters (end with '.'):";
while (*input != '.')
{
cin.getline(input, size);
}
}
I want the loop to exit after a '.' is entered and to ignore all input after the '.' on the rest of the line.
Lines 1-3: how does your function know that the argument array has 9999 elements? (It doesn't.)
Line 4: What is this variable supposed to do? (Because, currently, it does nothing.)
Lines 6-9: What you have written is:
6 7 8 9
while (the first character in the array is not a '.')
{
get an entire line of input into the array
}
To fix it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void getInput(char input[], int size) // array, and maximum number of elements in the array
{
int used = 0; // number of elements actually used in the array
char c; // a character read from input
cout << "Enter a sequence of characters (end with '.'): ";
while (cin.get(c)) // get a single character from the input
{
if (c is a '.') break;
what do I do to add c to the end of the array?
what do I have to do to 'used'for the next iteration?
if (used == size-1) break; // make sure not to read more characters than the array can hold
}
input[used] = 0; // Don't forget to null-terminate your C-strings.
}