473,786 Members | 2,304 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

get integer values using ifstream error.

when I use the following code to get integer values from file:
void getIntegers()
{
vector<ItemType items;
ifstream ifs("test.dat") ;
//考虑为items一次 分配空间。
ItemType item ;
while( !ifs.eof() )
{
ifs>>item;
items.push_back (item);
}
}
if test.dat is ended with a carriage return, "ifs>>item" will not fail
but doesn't change item's value. this is not I want.
using try...catch having no effect.

So is there an stardard way to get integer(float) from a file? the file
format is like this.
//////test.dat
101

22

35
//end with a carriage return

Nov 7 '06 #1
7 3912
Hi

zh*********@gma il.com wrote:
while( !ifs.eof() )
{
ifs>>item;
items.push_back (item);
}
This is an faq.
Please go and read http://www.parashift.com/c++-faq-lite/ before posting
questions. Thanks.

Markus

Nov 7 '06 #2
<zh*********@gm ail.comwrote in message
news:11******** **************@ m7g2000cwm.goog legroups.com...
>when I use the following code to get integer values from file:
void getIntegers()
{
vector<ItemType items;
ifstream ifs("test.dat") ;
//考虑为items一次 分配空间。
ItemType item ;
while( !ifs.eof() )
{
ifs>>item;
items.push_back (item);
}
}
if test.dat is ended with a carriage return, "ifs>>item" will not fail
but doesn't change item's value. this is not I want.
using try...catch having no effect.

So is there an stardard way to get integer(float) from a file?
eof() cannot be set prior to testing whether the next
item can be read or not. Also, failures other than eof
are possible.
And an exception will only be thrown if you configure the
stream accordingly...

Try the following loop:
while( ifs>>item )
items.push_back (item);

Even easier, if your file contains a simple array of values,
you can use istream_iterato r ( #include <iterator):

typedef std::istream_it erator<ItemType InItem;
std::vector<Ite mTypeconst items( (InItem(ifs)), InItem() );
// directly initializes the collection from the file
Note
- the collection can then (optionally) be 'const', which
is a good idea for safety if you don't edit the vector.
- the extra parenthesis around the first parameter is somehow
required for syntactic disambiguation with a function
declaration ( see "C++ most vexing parse" or a FAQ...)

hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

Nov 7 '06 #3
thanks!
an extra question:
how to read the first n elements of the file using the second solution?
"
typedef std::istream_it erator<ItemType InItem;
std::vector<Ite mTypeconst items( (InItem(ifs)), InItem() );
"

"Ivan Vecerina 写道:
"
<zh*********@gm ail.comwrote in message
news:11******** **************@ m7g2000cwm.goog legroups.com...
when I use the following code to get integer values from file:
void getIntegers()
{
vector<ItemType items;
ifstream ifs("test.dat") ;
//考虑为items一次 分配空间。
ItemType item ;
while( !ifs.eof() )
{
ifs>>item;
items.push_back (item);
}
}
if test.dat is ended with a carriage return, "ifs>>item" will not fail
but doesn't change item's value. this is not I want.
using try...catch having no effect.

So is there an stardard way to get integer(float) from a file?

eof() cannot be set prior to testing whether the next
item can be read or not. Also, failures other than eof
are possible.
And an exception will only be thrown if you configure the
stream accordingly...

Try the following loop:
while( ifs>>item )
items.push_back (item);

Even easier, if your file contains a simple array of values,
you can use istream_iterato r ( #include <iterator):

typedef std::istream_it erator<ItemType InItem;
std::vector<Ite mTypeconst items( (InItem(ifs)), InItem() );
// directly initializes the collection from the file
Note
- the collection can then (optionally) be 'const', which
is a good idea for safety if you don't edit the vector.
- the extra parenthesis around the first parameter is somehow
required for syntactic disambiguation with a function
declaration ( see "C++ most vexing parse" or a FAQ...)

hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com
Nov 7 '06 #4

zh*********@gma il.com wrote:
when I use the following code to get integer values from file:
void getIntegers()
{
vector<ItemType items;
ifstream ifs("test.dat") ;
//考虑为items一次 分配空间。
ItemType item ;
while( !ifs.eof() )
{
ifs>>item;
items.push_back (item);
}
}
if test.dat is ended with a carriage return, "ifs>>item" will not fail
but doesn't change item's value. this is not I want.
using try...catch having no effect.

So is there an stardard way to get integer(float) from a file? the file
format is like this.
//////test.dat
101

22

35
//end with a carriage return

you can use fscanf func

Nov 7 '06 #5
It's a solution, but considering the efficiency, I prefer to use stream
than fscanf.
"emil 写道:
"
zh*********@gma il.com wrote:
when I use the following code to get integer values from file:
void getIntegers()
{
vector<ItemType items;
ifstream ifs("test.dat") ;
//考虑为items一次 分配空间。
ItemType item ;
while( !ifs.eof() )
{
ifs>>item;
items.push_back (item);
}
}
if test.dat is ended with a carriage return, "ifs>>item" will not fail
but doesn't change item's value. this is not I want.
using try...catch having no effect.

So is there an stardard way to get integer(float) from a file? the file
format is like this.
//////test.dat
101

22

35
//end with a carriage return

you can use fscanf func
Nov 7 '06 #6
Hi

ni*********@gma il.com wrote:
It's a solution, but considering the efficiency, I prefer to use stream
than fscanf.
"emil 鍐欓亾锛
[...]
>you can use fscanf func
Again, _please_ read the FAQ ( http://www.parashift.com/c++-faq-lite/ )
before posting. In this case especially [5.4], where it says: "do not
top-post". Thanks.

Markus

Nov 7 '06 #7
<ni*********@gm ail.comwrote in message
news:11******** **************@ e3g2000cwe.goog legroups.com...
>thanks!
NB: please don't top-post, see
http://www.parashift.com/c++-faq-lit...t.html#faq-5.4
>an extra question:
how to read the first n elements of the file using the second solution?
"
typedef std::istream_it erator<ItemType InItem;
std::vector<It emTypeconst items( (InItem(ifs)), InItem() );
"
Sadly, I can't think of an obvious way to read a fixed number
of elements using the above approach - not using the standard
library alone.
Regrettably, I think in this case I would revert to using a loop:
std::vector<Ite mTypeitems(n);
for( unsigned i = 0 ; i<n ; ++i )
ifs >items[i];

Various C++ library implementations provide extensions that would also
help with this, for example: http://www.sgi.com/tech/stl/copy_n.html
std::vector<Ite mTypeitems;
copy_n( istream_iterato r<ItemType>(ifs ), n, back_inserter(i tems) );

It would also be possible to write an iterator wrapper to allow
writing:
typedef count_iterator< std::istream_it erator<ItemType InItem;
std::vector<Ite mTypeconst items( (InItem(ifs)), InItem(n) );

I don't know if the planned/official C++ library extensions (TR1, TR2,
or C++0x) include a facility that would support any of the above...

--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

Nov 7 '06 #8

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

Similar topics

6
3660
by: Herv? LEBAIL | last post by:
Hi everybody, I'm writing a program which use the <string>, <vector> and <ifstream> classes. Given an array of string, i.e vector<string> file_names, example : file_names = "file1.txt" file_names = "file2.txt" etc ...
4
3739
by: hall | last post by:
Hi. I ran across a bug in one of my problems and after spending some time tracking it down i found that the problem arose in a piece of code that essentially did this: ----------- ifstream in("in.txt"); if(!in) {cout << "error\n";} in.close(); if(!in) {cout << "error\n";} in.close(); if(!in) {cout << "error\n";}
2
4257
by: Peter Gordon | last post by:
Is using getline with a fstream reference covered in the standard? I have three C++ compilers on my system. Two of them compile the code below without warnings. The third returns the following error: t1.cpp: Error E2285 t1.cpp 14: Could not find a match for 'std::getline<charT,traits,Allocator>(std::ifstream,std::string)' in function A::readfun() *** 1 errors in Compile ***
13
3659
by: coinjo | last post by:
Is there any function to determine the length of an integer string?
4
2640
by: jm0 | last post by:
Hi, im developing this program, and then i ran into some trouble "oooh no!" hate to ask.. have search google and this page for something to spilt things up in arrays or whatever can be used, spent my half day trying to find a solution, but nothing :( then i agreed with my self that i have to ask. So her's the question/problem. Link to project: http://kawsper.dyndns.dk/~jmo/development/c++/projects/n0rdnat/ I have a data file called...
3
2359
by: khaleel.alyasini | last post by:
Hi, currently I'm working on DCT algorithm on C++. I was wondering if anyone out there could point me out how to seperate the pixel values into DCT blocks. Here, i have enclosed my source code(incomplete). specs: 1. seperates pixels values into block of 8x8 2. stores the values in a new pointer. #include <iostream.h> #include <fstream.h>
1
2338
by: James Lehman | last post by:
Hello. I want to write a program that reads AutoCAD shape (font) files. They are written with the convention that hexadecimal values have a leading zero and decimal values do not. All numbers can be negative or positive. All numbers can be stored in a single byte. My questions is: can ifstream extraction into an int see the leading zero and interpret the number as hex and can I ask the ifstream, right after the extraction, if the value I...
4
16240
by: Gary Wessle | last post by:
Hi I am writing a code to open a space delimited data file, return the number of rows and columns, as well as return the nth column where n is user define number. I put all the cells in a loooong vector and loop in an incremental way to select the column of choice, here is the code which works but gives a warning ****************************************************************
4
12870
by: marathoner | last post by:
I tried your advice, and replaced "ifstream" with "std::ifstream". I also replaced instances of "ofstream" with "std::ofstream". Those syntax errors were resolved. When I added "std" to the following statement: m_InFile.open(m_sFileName, ios::in | ios::binary); which became m_InFile.open(m_sFileName, std::ios::in | std::ios::binary); I get the following errors:
0
9491
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
10357
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10104
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
9959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8988
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梡lanning, coding, testing, and deployment梬ithout 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
6744
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
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4063
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
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.