-1

I need to get a clue in how know when to stop storing a string from a file after i hit a space between the words. After i open a file and read it, for example: the first line that is there is:427 671 +. I need to store "427" in an array of int, same with "671" and "+"in a variable.

So far i have figure out how to read the whole line and print it but the problem i have is to read char by char and store it before i hit a space.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <Laboratorio.h>
#include <string.h>
int main(int argc, char **argv) {
  FILE *datos;
  FILE *resultados;
  char bin[64]="",hex[16]="";
  int oct[21];
  ep = fopen ( argv[1], "r" );
  if (ep==NULL) {
        printf("Archivo vacio.");
    return 0;
    }else{
    while (fgets(bin,64,ep)!=NULL){
      printf("%s",bin);
    }
  fclose(ep);
}
}
bronze56k
  • 55
  • 1
  • 6
  • 1
    If you fail to open the file, you should print the error message to stderr, and return a non-zero value. eg `if(ep==NULL) { perror(argv[1]); return EXIT_FAILURE;}` – William Pursell Jul 23 '16 at 22:46
  • Use [`strtok()`](http://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c) to split whenever you encounter a white space. – Raktim Biswas Jul 23 '16 at 22:56
  • 1
    You have many of options. One is to use `scanf()` and the `%s` conversion specifier; it stops at white space each time. Another is to use tokenizing code on lines as you read each line — `strtok()` et al (use `strtok_r()` or `strtok_s()` if they're available, but these all modify the original string), or functions such as `strpbrk()` and `strspn()` and `strcspn()`. There are numerous question on SO about postfix to infix conversion and related issues; they may well help too. – Jonathan Leffler Jul 23 '16 at 23:50

1 Answers1

1

The simplest way to do so would be to have a char variable and store each char into it one by one like so:

while ((ch = getc(stream)) != EOF) 
{
// do stuff with char
}

after you get the char you can decide what to do with it, compare it to 32 (space) to know when to stop.

if the char is a numeral you can place it in a buffer until you reach a space, then all you need to do is use the function atoi which receives a pointer to a string, and returns an int representation of the string. for example: turns the string "432" to an int 432.

monkeyStix
  • 620
  • 5
  • 10