fscanf in text file

May 13, 2008 at 2:44am
i need help to scan the following in text file

56567-64-654-546

how can i get each integer without (-)..tq.
May 13, 2008 at 10:46am
If it's always of the format int - int - int - int then you could
1
2
3
4
5
6
unsigned int i1, i2, i3, i4;
if( fscanf( fd, "%u-%u-%u-%u", &i1, &2, &i3, &i4 ) != 4 ) {
    std::cerr << "File format error." << std::endl;
} else {
    // Got all 4!
}

May 13, 2008 at 3:43pm
If U don't know how many "-" are there in a single line then U have to manipulate the same by Ur own logic.
May 13, 2008 at 7:02pm
IMO. You are better off reading the entire line, then splitting it into a string array using "-" as the separator.

http://www.cplusplus.com/reference/clibrary/cstring/strtok.html
shows you how to achieve this.

fscanf is a C implementation, it's not overly flexible and generating the format string opens you up to format string exploitation.
May 13, 2008 at 9:34pm
There is no danger in his format string. The worst that can happen is the input is not a number, at which point *scanf terminates anyway.

Also, strtok() is not a very friendly alternative (as it is obnoxious to use and it destroys the input string). Everything can be done very easily using standard C++. And you are assuming that the entire string is by itself on a line (which it might not be). The only reason to go this route over directly reading the istream would be to separate the time of input and time of parsing.

Assuming input is always properly formatted or bust
1
2
3
4
  unsigned int num[4];
  char c;  // throwaway var to catch '-'
  cin >> num[0] >> c >> num[1] >> c >> num[2] >> c >> num[3];
  if (!cin) fooey();

You can also use standard containers instead of an array or a collection of individual variables:
1
2
  vector<unsigned int> num( 4 );
  ...


Hope this helps.
Topic archived. No new replies allowed.