Alla _
2015-12-18 12:10:53 UTC
Hello!
I have a technical question, and I failed to google it correctly, therefore
was unable to get answer from the web.
If the program has a variable i, which is an array index, and this variable
has acquired some value, and after that I would like to use a for loop that
starts from the last available value of i, how do I put that value in the for
loop?
Here is an example. The job is done by the while loop within get_line function,
and I would like to achieve the same result with the for loop, for educational
purpose merely. Obviously, I can't omit the initialization.
for (???; isspace(s[i]); i--)
;
Test program:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char line[1000] = {0};
int length = get_line(line, 1000);
printf("%i: %s\n", length, line);
return 0;
}
/* getline: read a line into s, return length */
int get_line (char s[], int lim)
{
int c;
int len;
int i = 0;
while ((c = getchar()) != EOF && isspace(c))
;
s[i] = c;
for (i = 1; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
{
s[i] = c;
}
if (c == '\n')
{
s[i] = c;
}
/* skip trailling spaces */
while (isspace(s[i])) /* here I would like to use the for loop */
{
i--;
}
/* for (???; isspace(s[i]); i--)
;
*/
len = ++i;
s[i++] = '\n';
s[i] = '\0';
return len;
}
Thank you!
I have a technical question, and I failed to google it correctly, therefore
was unable to get answer from the web.
If the program has a variable i, which is an array index, and this variable
has acquired some value, and after that I would like to use a for loop that
starts from the last available value of i, how do I put that value in the for
loop?
Here is an example. The job is done by the while loop within get_line function,
and I would like to achieve the same result with the for loop, for educational
purpose merely. Obviously, I can't omit the initialization.
for (???; isspace(s[i]); i--)
;
Test program:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char line[1000] = {0};
int length = get_line(line, 1000);
printf("%i: %s\n", length, line);
return 0;
}
/* getline: read a line into s, return length */
int get_line (char s[], int lim)
{
int c;
int len;
int i = 0;
while ((c = getchar()) != EOF && isspace(c))
;
s[i] = c;
for (i = 1; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
{
s[i] = c;
}
if (c == '\n')
{
s[i] = c;
}
/* skip trailling spaces */
while (isspace(s[i])) /* here I would like to use the for loop */
{
i--;
}
/* for (???; isspace(s[i]); i--)
;
*/
len = ++i;
s[i++] = '\n';
s[i] = '\0';
return len;
}
Thank you!