Reputation: 239
I'm trying to print a string of chars from an array and end the loop whenever I press the "Enter" key.
int i;
char charArry[MAXARY];
printf("Input an array of chars: \n\n");
for (i = 0; i < MAXARY && charArry[i] != 13; i++)
{
scanf(" %c", &charArry[i]);
}
for (i = 0; i < MAXARY; i++)
{
printf(" %c", charArry[i]);
}
For some reason whenever I press the Enter key it just goes to a new line instead of breaking the loop. Any suggestions?
P.S MAXARY is a constant for the array length, currently 20.
Upvotes: 1
Views: 5966
Reputation: 331
Your close to having this working. Whilst I agree the use of scanf
should be avoided, see: Why does everyone say not to use scanf? What should I use instead?, the reason your program doesn't do what you expect is due to a logic error.
Your for loop states:
for (i = 0; i < MAXARY && charArry[i] != 13; i++)
Now recapping how a for loop works, you have:
1. initalization (i=0)
2. conditional check (i < MAXARY && charArry[i] != 13)
3. conditional block (scanf)
4. increment (i++)
5. return to 2
You'll note your charArray[i] != 13
check is happening after i
has been incremented. Hence your not checking against the character you just read but the next character in charArray[i]. This is why your never breaking your loop at the \r
character.
A recommended fix would be:
for (i = 0; i < MAXARY; i++)
{
int result = scanf("%c", &charArry[i]);
if( result != 1 || charArry[i] == '\n' )
break;
}
Which checks scanf was successful and charArry when i
is the character that was read.
Also note as chux has pointed out the \r
character is a carrage return, not the newline. Hence this check will only work if your working on windows (as unix doesn't use \r
). If you want to be platform independant use \n
Upvotes: 2
Reputation: 153338
For some reason whenever I press the Enter key it just goes to a new line instead of breaking the loop.
The space in the format scanf(" %c", &charArry[i]);
directs scanf()
to consume and discard all optional leading white-space. charArry[i]
will never be assigned 13
as 13 is typically '\r'
, a white-space.
An enter key is usually translated to '\n'
.
Do not test values that have not been assigned @Red Alert
// v---------v not assigned yet.
for (i = 0; i < MAXARY && charArry[i] != 13
Repaired code
int i;
char charArry[MAXARY];
printf("Input an array of chars: \n\n");
for (i = 0; i < MAXARY; i++) {
if (scanf("%c", &charArry[i]) != 1) break; // End of file or error occurred
// If enter key encountered
// Usualy the charArry[i] == '\r' is not needed.
if (charArry[i] == '\n' || charArry[i] == '\r') break;
}
// Only print out characters that were read.
int j;
for (j = 0; j < i; j++) {
printf("%c", charArry[j]);
}
Upvotes: 2