C/C++ reading line at a time -
C/C++ reading line at a time -
i trying solve programming problem of site , 1 had next statement:
read string , parse number, char 'l' can considered number 1 , chars 'o' , 'o' can considered number 0, commas , spaces accepted in input ignored, if other character found output error...
so... since there can spaces in lines, used gets (the documentation says removes new line , puts terminator)...
my sequence of if test if number, if acceptable letter, checks if not comma or space... , found out entering in lastly if though there wasn't character should lead there changed printf within print
printf("%d error", st[k]);
and outputs 13: carriage return... tried compiler here
#include <cstdio> #include <cstring> #include <cstdlib> int main() { char st[100]; char buf[100]; int k, i; long long int num; ops: while(gets(st)) { for(k = = 0; st[k]; k++) if(st[k] >= '0' && st[k] <= '9') buf[i++] = st[k]; else if(st[k] == 'o' || st[k] == 'o') buf[i++] = '0'; else if(st[k] == 'l') buf[i++] = '1'; else if(st[k] != ',' && st[k] != ' ') { printf("error\n"); goto ops; } // remaining code comes here... }
the input sample had next lilnes:
lo6 234,657
hi ,,,,,5,,5, 4
2200000000
00
should utilize other function read instead?
any suggestions on how avoid damn carriage return?
the statemente problem can seen here if want more detail thanks
edit:
i'm asking because there seem difference between compiler i'm using , compiler website using, 1 time submitted code wasn't generating right output on mine thought code correct... , passed. after it, tried code on linux virtual machine , right gcc on windows failed... characters away should be
the thing is:
the preferred method of line input getline
. if not know width of input beforehand, getline
allocate space if set buffer pointer null
.
since indicate have experience in c, next show how step through input string , parse in manner want. while there many ways handle parsing strings, hard beat assigning pointer origin of string , advancing downwards string until reach null-terminating character (unsigned 0
, or char '\0'
). if have questions after looking over, ask:
#include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { char *buffer = null; size_t n = 0; ssize_t len; char *ptr = null; char *output = null; int idx = 0; printf ("\nenter string below: ([ctrl + d] on blank line end)\n"); while ((len = getline (&buffer, &n, stdin)) != -1) { ptr = buffer; idx = 0; output = malloc (sizeof (char) * len); while (*ptr != 0) { if (*ptr >= 48 && *ptr <= 57) output [idx++] = *ptr; if (*ptr == 'i') output [idx++] = '1'; if (*ptr == 'o' || *ptr == 'o') output [idx++] = '0'; ptr++; } output [idx] = 0; printf ("\n valid output: %s\n\n", output); free (output); } homecoming 0; }
output:
enter string below: ([ctrl + d] on blank line end) sting has 12345 aeiou aeiou,,,,,commas, , 99, end. valid output: 123450100990
c++ c carriage-return
Comments
Post a Comment