473,796 Members | 2,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading numbers from a file

Hi,
I'm reading a string of numbers from a file (using Borland C++ Builder
6), and I'm doing it like this: first I use FileRead to store all the
data in the file to a char* variable (appropriately called 'data').
Then, I read every number using

char *ptr;
int value;

[...]

ptr = &data[position];
sscanf (ptr, "%i", &value);
position += IntToStr(value) .Length();
numbers[i] = value;

(All of it inside of a loop, of course).
This method seems to be working OK, but Borland CodeGuard tells me that
there's an access overrun in each sscanf call, so I guess there is a
better way of doing it. Could you please help me?
Big thanks,

LuTHieR

Jun 10 '06 #1
10 3296
LuTHieR wrote:
Hi,
I'm reading a string of numbers from a file (using Borland C++ Builder
6), and I'm doing it like this: first I use FileRead to store all the
data in the file to a char* variable (appropriately called 'data').
Then, I read every number using

char *ptr;
int value;

[...]

ptr = &data[position];
sscanf (ptr, "%i", &value);
position += IntToStr(value) .Length();
numbers[i] = value;

(All of it inside of a loop, of course).
This method seems to be working OK, but Borland CodeGuard tells me that
there's an access overrun in each sscanf call, so I guess there is a
better way of doing it. Could you please help me?
Big thanks,

LuTHieR


In C++ you should try avoid using the C I/O functions unless you have a
good reason to be using them. sscanf and its variants are notoriously
easy to use incorrectly. Here is an example of how to do the same using
C++'s stringstreams. Modify to your needs:

#include <iostream>
#include <sstream>

int main()
{
char data[] = "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47" ;
std::istringstr eam ss(data) ;
int i ;
while (ss >> i)
std::cout << i << std::endl ;
}

--
Alan Johnson
Jun 10 '06 #2
Thanks :)
One more question...if data contains a String before the actual data
(something like data[] = "label 1 2 3 4 5 6 7 8"), how can I easily
read it?
Thanks again

LuTHieR

Alan Johnson ha escrito:
LuTHieR wrote:
Hi,
I'm reading a string of numbers from a file (using Borland C++ Builder
6), and I'm doing it like this: first I use FileRead to store all the
data in the file to a char* variable (appropriately called 'data').
Then, I read every number using

char *ptr;
int value;

[...]

ptr = &data[position];
sscanf (ptr, "%i", &value);
position += IntToStr(value) .Length();
numbers[i] = value;

(All of it inside of a loop, of course).
This method seems to be working OK, but Borland CodeGuard tells me that
there's an access overrun in each sscanf call, so I guess there is a
better way of doing it. Could you please help me?
Big thanks,

LuTHieR


In C++ you should try avoid using the C I/O functions unless you have a
good reason to be using them. sscanf and its variants are notoriously
easy to use incorrectly. Here is an example of how to do the same using
C++'s stringstreams. Modify to your needs:

#include <iostream>
#include <sstream>

int main()
{
char data[] = "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47" ;
std::istringstr eam ss(data) ;
int i ;
while (ss >> i)
std::cout << i << std::endl ;
}

--
Alan Johnson


Jun 10 '06 #3
Don't bother answering, it was as simple as using the >> operator to a
string type.
Thanks again

LuTHieR

LuTHieR ha escrito:
Thanks :)
One more question...if data contains a String before the actual data
(something like data[] = "label 1 2 3 4 5 6 7 8"), how can I easily
read it?
Thanks again

LuTHieR

Alan Johnson ha escrito:
LuTHieR wrote:
Hi,
I'm reading a string of numbers from a file (using Borland C++ Builder
6), and I'm doing it like this: first I use FileRead to store all the
data in the file to a char* variable (appropriately called 'data').
Then, I read every number using

char *ptr;
int value;

[...]

ptr = &data[position];
sscanf (ptr, "%i", &value);
position += IntToStr(value) .Length();
numbers[i] = value;

(All of it inside of a loop, of course).
This method seems to be working OK, but Borland CodeGuard tells me that
there's an access overrun in each sscanf call, so I guess there is a
better way of doing it. Could you please help me?
Big thanks,

LuTHieR


In C++ you should try avoid using the C I/O functions unless you have a
good reason to be using them. sscanf and its variants are notoriously
easy to use incorrectly. Here is an example of how to do the same using
C++'s stringstreams. Modify to your needs:

#include <iostream>
#include <sstream>

int main()
{
char data[] = "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47" ;
std::istringstr eam ss(data) ;
int i ;
while (ss >> i)
std::cout << i << std::endl ;
}

--
Alan Johnson


Jun 10 '06 #4
LuTHieR wrote:
Thanks :)
One more question...if data contains a String before the actual data
(something like data[] = "label 1 2 3 4 5 6 7 8"), how can I easily
read it?


Please don't top-post. Your comments belong following or interspersed
with properly trimmed quotes. See below for further information:
<http://www.parashift.c om/c++-faq-lite/how-to-post.html#faq-5.4>


Brian
Jun 10 '06 #5

Default User ha escrito:
LuTHieR wrote:
Thanks :)
One more question...if data contains a String before the actual data
(something like data[] = "label 1 2 3 4 5 6 7 8"), how can I easily
read it?


Please don't top-post. Your comments belong following or interspersed
with properly trimmed quotes. See below for further information:
<http://www.parashift.c om/c++-faq-lite/how-to-post.html#faq-5.4>


Brian


Sorry 0:-)

Jun 10 '06 #6
> In C++ you should try avoid using the C I/O functions unless you have a
good reason to be using them. sscanf and its variants are notoriously
easy to use incorrectly. Here is an example of how to do the same using
C++'s stringstreams. Modify to your needs:

#include <iostream>
#include <sstream>

int main()
{
char data[] = "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47" ;
std::istringstr eam ss(data) ;
int i ;
while (ss >> i)
std::cout << i << std::endl ;
}

--
Alan Johnson


I must be really dumb :S Basing on the example you gave me, I was
trying to read many lines from the string, but on the second iteration
of the for loop, ss2 >> j evaluates to false, thus outputting just the
first line of the data string, and I can't figure out why. I guess the
problem is the use of the str method, but I don't know how to assign
the line variable to the istringstream in another way. Here's the code:
#include <iostream>
#include <sstream>

int main()
{
char data[] = "2 3 5 7 11 13\n 17 19 23 29 31\n 37 41 43 47" ;
char line[20];
int i,j;
std::istringstr eam ss(data);
std::istringstr eam ss2;

for (i=0; i<3; i++) {
ss.getline(line , 20);
ss2.str(line);
while (ss2 >> j)
std::cout << j << std::endl;
}
}

Thanks in advance.

Jun 11 '06 #7
LuTHieR wrote:
In C++ you should try avoid using the C I/O functions unless you have a
good reason to be using them. sscanf and its variants are notoriously
easy to use incorrectly. Here is an example of how to do the same using
C++'s stringstreams. Modify to your needs:

#include <iostream>
#include <sstream>

int main()
{
char data[] = "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47" ;
std::istringstr eam ss(data) ;
int i ;
while (ss >> i)
std::cout << i << std::endl ;
}

--
Alan Johnson


I must be really dumb :S Basing on the example you gave me, I was
trying to read many lines from the string, but on the second iteration
of the for loop, ss2 >> j evaluates to false, thus outputting just the
first line of the data string, and I can't figure out why. I guess the
problem is the use of the str method, but I don't know how to assign
the line variable to the istringstream in another way. Here's the code:
#include <iostream>
#include <sstream>

int main()
{
char data[] = "2 3 5 7 11 13\n 17 19 23 29 31\n 37 41 43 47" ;
char line[20];
int i,j;
std::istringstr eam ss(data);
std::istringstr eam ss2;

for (i=0; i<3; i++) {
ss.getline(line , 20);
ss2.str(line);
while (ss2 >> j)
std::cout << j << std::endl;
}
}

Thanks in advance.


When the while loop ends, it is because ss2 has reached EOF (or end of
string, as the case may be), and its failbit is set. You need to clear
the failbit, which you can do by calling ss2.clear() at the beginning of
the for loop. However, you can avoid the issue completely by
constructing ss2 inside the for loop.

While I'm making suggestions, let's also get rid of the arbitrary number
20 for a line length, by using std::string and std::getline. Making
both of these changes, your code will look something like:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
std::string data = "2 3 5 7 11 13\n 17 19 23 29 31\n 37 41 43 47";
std::istringstr eam ss(data);
int j;

for (size_t i=0; i<3; i++)
{
std::string line;
std::getline(ss , line);
std::istringstr eam ss2(line);
while (ss2 >> j)
std::cout << j << std::endl;
}
}
Unless you have a reason, though, there is no need to process this on a
line by line basis. operator>> will skip newlines just like any other
whitespace, and you could reduce this to:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
std::string data = "2 3 5 7 11 13\n 17 19 23 29 31\n 37 41 43 47";
std::istringstr eam ss(data);
int j ;

while (ss >> j)
std::cout << j << std::endl ;
}

--
Alan Johnson
Jun 11 '06 #8
In article <1149954290.927 527.16870
@h76g2000cwa.go oglegroups.com> , gr************* @gmail.com
says...
Hi,
I'm reading a string of numbers from a file (using Borland C++ Builder
[ ... ]
This method seems to be working OK, but Borland CodeGuard tells me that
there's an access overrun in each sscanf call, so I guess there is a
better way of doing it. Could you please help me?


[...and elsethread mentioned wanting to ignore other data
in the file]

You've gotten a number of replies, but I thought I'd add
one more way this could be done. At least as I understand
the situation, you only want to read the numbers from the
file, and ignore everything else.

One way to handle this would be to create a locale to
reflect that for your purposes, the file contains only
numbers (digits) and other "stuff" you're going to ignore
between the digits. From a viewpoint of reading the
numbers, everything is basically the same as whitespace
-- it separates one number from another, but otherwise
has no meaning. Therefore, we start by creating a ctype
facet that says it IS whitespace:

class number_only: std::ctype<char > {
number_only() : std::ctype<char >(get_table() ) {}
static std::ctype_base ::mask const *get_table() {
static std::ctype_base ::mask *rc;

if ( rc == 0) {

// create a character classification table
rc = new std::ctype_base ::mask
[std::ctype<char >::table_size];

// say that _everything_ is whitespace
std::fill_n(rc, std::ctype,char >::table_size ,
std::ctype_base ::space);

// except for [0-9]:
for (int i='0'; i<='9'; i++)
rc[i] = std::ctype_base ::digit;
]
return rc;
}
};

From there, we imbue the stream with a locale using that
facet, and we can just treat it as a file of numbers:

int main() {
std::ifstream x(wherever);

number_only n;
x.imbue(std::lo cale(std::local e(), n);

// now we can read in numbers, and everything
// else is ignored automagically.
std::vector<int > numbers;

// read in all the numbers:
std::copy(std:: istream_iterato r<int>(x),
std::istream_it erator<int>(),
std::back_inser ter(numbers));

// just for grins, we'll display them, one per line:
std::copy(numbe rs.begin(), numbers.end(),
std::ostream_it erator<int>(std ::cout, "\n"));

return 0;
}

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 12 '06 #9
Alan Johnson wrote:
When the while loop ends, it is because ss2 has reached EOF (or end of
string, as the case may be), and its failbit is set. You need to clear
the failbit, which you can do by calling ss2.clear() at the beginning of
the for loop. However, you can avoid the issue completely by
constructing ss2 inside the for loop.

While I'm making suggestions, let's also get rid of the arbitrary number
20 for a line length, by using std::string and std::getline. Making
both of these changes, your code will look something like:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
std::string data = "2 3 5 7 11 13\n 17 19 23 29 31\n 37 41 43 47";
std::istringstr eam ss(data);
int j;

for (size_t i=0; i<3; i++)
{
std::string line;
std::getline(ss , line);
std::istringstr eam ss2(line);
while (ss2 >> j)
std::cout << j << std::endl;
}
}
Unless you have a reason, though, there is no need to process this on a
line by line basis. operator>> will skip newlines just like any other
whitespace, and you could reduce this to:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
std::string data = "2 3 5 7 11 13\n 17 19 23 29 31\n 37 41 43 47";
std::istringstr eam ss(data);
int j ;

while (ss >> j)
std::cout << j << std::endl ;
}

--
Alan Johnson


Thanks once again. In fact, the line by line processing is required, I
need to know how many numbers have been read in every line and output
an error if there are more/less numbers than expected. Oh, and the line
length set to 20 was only for the example :)
Regards,

LuTHieR

Jun 12 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2058
by: opt_inf_env | last post by:
Hello, I would like to solve the following problem. On the server side I have a file with a sequence of natural numbers (1, 2, 3, 4, 5, ...., n). Each user, after some action, adds new number (n+1, where n is the last number in the file) to the end of file. To do this user has to open the file for reading, read the last number, perform corresponding manipulations with the extracted last number and add result to the end of the file...
2
5246
by: adpsimpson | last post by:
Hi, I have a file which I wish to read from C++. The file, created by another programme, contains both text and numbers, all as ascii (it's a .txt file). A sample of the file is shown below: << LEDAR V1.3 - Real Time Detection >> <LEFT 144> <TOP 165> <RIGHT 265> <BOTTOM 376>
3
3403
by: muser | last post by:
With the following code I'm trying to read a text file (infile) and output inaccuracies to the error file (printerfile). The text file is written and stored on disk, while the printerfile has to be created when the program executes. But the compile keeps reading that it can't find the text file. Karl you wrote the original program from which this one is but a poor copy, can you or anyone else enlighten me as to why yours worked and mine...
3
9623
by: Tanuki | last post by:
Hi All: I encounter a programming problem recently. I need to read a binary file. I need to translate the binary data into useful information. I have the format at hand, like 1st byte = ID, next 4 byte (int) = serial number etc. The first problem is Big Endian/ Little Endian problem. I can decipher if the format is big or little endian. But got confuse as to how to decipher the data.
9
2123
by: EkteGjetost | last post by:
I would like to first apologize to those of you who read my last post "desperately need help". As a regular on other forums i can understand how aggravating it would be to have someone come on who obviously doesn't know the community and asks for people to do their work for them. So i've come much more prepared this time. What my problem is, is that i need to write a program that will count the number of alphabetic characters, numbers,...
3
24596
by: Millennium Falcon | last post by:
Hi! Help is kindly requested in reading floating point numbers from a text file. File is organized like this : 2000 // number of data -1.00000 -2.000000 -0.008944 // x, y & z-coordinates to the end of file ... ...
11
6085
by: Girish Sahani | last post by:
I wrote the following code to concatenate every 2 keys of a dictionary and their corresponding values. e.g if i have tiDict1 = tiDict1 = {'a':,'b':} i should get tiDict2={'ab':} and similarly for dicts with larger no. of features. Now i want to check each pair to see if they are connected...element of this pair will be one from the first list and one from the second....e.g for 'ab' i want to check if 1 and 3 are connected,then 1 and...
6
3714
by: Nick | last post by:
Hiya, Am having a few problems with StreamReader. I'm trying to open a text file, and read 5 columns, and put them into an array, and then do a calculation and read the next line of data, and do a calc etc. I can open the text file and display it fine, but cant seem to get each line into an array to do the maths :(
4
2081
by: GeekBoy | last post by:
I am reading a file of numbers using for loops. The numbers are in a grid as follows: 8 36 14 11 31 17 22 23 17 8 9 33 23 32 18 39 23 25 9 38 14 38 4 22 18 11 31 19 16 17 9 32 25 8 1 23
0
9684
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9530
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10236
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10182
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6793
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.