Results 1 to 2 of 2
I need this program to pause where it says "Enter line: " The problem is every time I run the program it goes to Print Line iv over instead of ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 09-07-2011 #1Just Joined!
- Join Date
- Sep 2011
- Posts
- 2
problem with scanf()
I need this program to pause where it says "Enter line: " The problem is every time I run the program it goes to Print Line iv over instead of pausing for the input at Enter line.
Code:#include <stdio.h> #define MAXLINE 1000 int get_line(char line[], int maxline); int get_int(); main() { int len, max; char line[MAXLINE]; max = get_int(); while ((len = get_line(line, MAXLINE)) > 0) { if (len > max) printf("%s", line); max = get_int(); } } int get_line(char s[], int lim) { int c, i; printf("Enter line: "); for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } int get_int() { int i; printf("Print line if over: "); scanf("%d", &i); return i; }
- 09-08-2011 #2
I suspect the line scanf() in get_int() is creating the problem. When you type some char and press enter ('\n') ..when it goes to get_line() for loop c has the value '\n' and it breaks out of the loop.
So I changed it from '\n' to '$'for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '$'; ++i)
s[i] = c;
if (c == '$') {
s[i] = c;
output-
Probably you can take it from herePrint line if over: 1
Enter line: hello$
hello$Print line if over: 2
Enter line: world$
world$
First they ignore you,Then they laugh at you,Then they fight with you,Then you win. - M.K.Gandhi
-----
FOSS India Award winning ext3fs Undelete tool www.giis.co.in. Online Linux Terminal http://www.webminal.org


Reply With Quote
