473,388 Members | 1,496 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Reading in text file in c++

I've 13 int number as a list in txt file.
34
55
99
120
57
45
49
30
32
21
56
22
0


The last value is a 0 and is NOT one of the values to be used in any calculation . I am supposed to create only one array as global variable.
So what would be the logic behind(with code) to read all the numbers from the file except the last one (i.e, 0) and put them in globally created array.

and if 0 is situated between 45 and 49; in that case we have to take that 0 as the value of array.

Thank you !
I hope I'll get solution soon...
Apr 5 '10 #1

✓ answered by jkmyoung

Why not? If you make the array of size 21, it handles up to 20 integers. If you make the array of size 20, it only handles up to 19 integers. Doesn't logic follow that you should make the array of size 21? Challenge your own assumptions man.

Either that or add a pesky if clause inside the loop.

14 4833
manontheedge
175 100+
first, look up "fstream" to find out how to read a text file and store the data ( there are other ways, but fstream is one of them )

then, learn about arrays so you see how you can put values in it ( the values from the text file )

try to get the file reading and array storing to work and people will be much more likely to help you out. If you have problems with either of those, after you've read about it and tried it, post your code and let us know what specifically you're having trouble with.
Apr 5 '10 #2
weaknessforcats
9,208 Expert Mod 8TB
If you know there are ints in the file and you need only 12, you might try:

myfile >> arr[0] >> arr[1] etc...

or use a loop where myfile is an ifstream.
Apr 5 '10 #3
If I dont know how many number are there in the file. It might more than 12 might be 14 or 16 or 17 whatever (within 20). Here I've to pick up the numbers up to second last from a file.
like I already create global array as

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
const int size = 20;
int arr[20];
int count=0;
fstream infile;
infile.open("c:/C++/array1.txt");
if(!infile)
{
cout<<"Error! Can't open the file.";
}

do
{
infile>>arr[count]; //so here what code will help me to read up to second last integer value from the file.
count++;
}while(!infile.eof());

cout<<endl<<"Size of the array is:"<<count;

for(int i=0;i<count;i++)
{
cout<<endl<<"arr["<<i<<"] = "<<arr[i];
}

cout<<endl;
infile.close();
return 0;
}
Apr 6 '10 #4
weaknessforcats
9,208 Expert Mod 8TB
You may need to seek to the end of the file and then back up two integers and then read the file backwards to the begininng.

Expand|Select|Wrap|Line Numbers
  1. ifstream myfile;
  2. myfile.seekg(SEEK_END - 2*sizeof(int));
The beginning of the file is SEEK_SET.

This assumes no whitespeace between the ints.
Apr 6 '10 #5
wher I can use the code you send me

your code is below

ifstream myfile;
myfile.seekg(SEEK_END - 2*sizeof(int));

in my code bellow

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
const int size = 20;
int arr[20];
int count=0;
fstream infile;
infile.open("c:/C++/array1.txt");
if(!infile)
{
cout<<"Error! Can't open the file.";
}

do
{
infile>>arr[count]; //so here what code will help me to read up to second last integer value from the file.
count++;
}while(!infile.eof());

cout<<endl<<"Size of the array is:"<<count;

for(int i=0;i<count;i++)
{
cout<<endl<<"arr["<<i<<"] = "<<arr[i];
}

cout<<endl;
infile.close();
return 0;
}
Apr 6 '10 #6
weaknessforcats
9,208 Expert Mod 8TB
do
{
infile>>arr[count]; //so here what code will help me to read up to second last integer value from the file.
count++;
}while(!infile.eof());
This will read all of the integers in the file. But: a) your arr must be large enough to hold all the ints (currently it's too small) and b) the count will be incremented before the end of file is tested. Therefore, decrement count when you leave the loop.

So, if you read 10 ints then you can work with the first 8 so satisfy the "up the second from the end" requirement.

With reading, you cannot read the file correctly unless you already know the format. So unless you know ahead of time how mnay ints there are, you have no choice but to read them all in order to find out which are the last two.
Apr 6 '10 #7
Its ok counter part I will handle it. but isn't there any function in fstream
library that will help me to loop through the text file till second last of the number list.
The actual question is like this
Q. Write a program that will manipulate an array. Your program should handle up to 20 integer numbers. Declare the array as a global variable. (This is the only time you should use a global variable.)



For each print out produced below, label the results. Also print your output in the order listed below.



Write a function for each part. You should have a single program with multiple functions.

_____________________________



1. Read the integer values into the array from a file. The last value is a 0 and is NOT one of the values to be used in any calculation below. A sample input file is provided with the assignment.


2. Print out all the values in the array with no more than 5 numbers per output line.



3. Print out the average of the numbers.



4. Print out how many numbers are larger than the average and how many are smaller than the average. Pass average as a parameter to the function..



5. For every odd location in the array, subtract it from the previous even location and store results in the even location. Print out all values in the array (a previous requirement)



6. Print out the average for the new array.



7. Convert every negative numbers to positive numbers. Print out the array.



8. Swap the first number in the array with the last number in the array. Print out the array.



9. Print out the average for the new array.




input file:




34
55
99
120
57
45
49
30
32
21
56
22
0
Apr 6 '10 #8
jkmyoung
2,057 Expert 2GB
With something tricky like the average, you'll have to keep track of all your inputs, because one number at the end could throw the average off.

To make input simpler, make your array of size 21 so that 0 can fit in the 21st spot (index 20) if needed. After you read in the final 0, just decrement the counter by 2 to let you know your maximum index, (1 for the 0, and 1 because of the extra count++ at the end), before processing your numbers.
Apr 6 '10 #9
But It has already been said in the question that Your program should handle up to 20 integer numbers. Declare the array as a global variable..
In the real code I am not supposed to make the array of size 21. Thank you!
Apr 6 '10 #10
jkmyoung
2,057 Expert 2GB
Why not? If you make the array of size 21, it handles up to 20 integers. If you make the array of size 20, it only handles up to 19 integers. Doesn't logic follow that you should make the array of size 21? Challenge your own assumptions man.

Either that or add a pesky if clause inside the loop.
Apr 6 '10 #11
I did it! Thanks for encouragement see u with next Quest...
Apr 7 '10 #12
weaknessforcats
9,208 Expert Mod 8TB
If you make the array of size 21, it handles up to 20 integers.
Maybe I am missing something but an array of size 21 will handle 21 integers.
They will be identified as elements 0 to 20.

Therefore, and array of 20 is all that's required here.
Apr 7 '10 #13
jkmyoung
2,057 Expert 2GB
If you have an array of 20, you have to constantly check after each element:
"Am I done?"
And EVEN then you need to still read in the last 0 element.
An array of 21 holds 20 values plus a "Sentinel" value of 0.

Benefits of array[20]:
non-element data is never read into data array.
May be easier to understand.
1 less array space needed.
You never read 0 into your calculations.
Handles error input better

Detriments:
Slower, requiring extra check every iteration.
Requires extra boolean space
Less elegant code.
If you think of 0 as a "sentinel" ending value then there is no disconnect.
Must detriment the counter anyways after use.

To be honest, I was just trying to give the original poster the quickest way to solve their problem without a lot of explanation and code changes.
Apr 7 '10 #14
weaknessforcats
9,208 Expert Mod 8TB
Ah, I see.

However, a sentinel value of 0 is still a valid integer value. The entire array could be filled with 0's.

In this case a counter for the number of elements that are active in the array may be safer. Especially if there are multiple 0 values.
Apr 7 '10 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Suresh Kumaran | last post by:
Hi All, Does anybody know the sytax in VB.NET to write the contents of a multiline text box to a text file? Appreciate help. Suresh
1
by: fabrice | last post by:
Hello, I've got trouble reading a text file (event viewer dump) by using the getline() function... After 200 - 300 lines that are read correctly, it suddenly stops reading the rest of the...
19
by: Lionel B | last post by:
Greetings, I need to read (unformatted text) from stdin up to EOF into a char buffer; of course I cannot allocate my buffer until I know how much text is available, and I do not know how much...
0
by: Eric Lilja | last post by:
Hello, I have a text file that contains a number of entries describing a recipe. Each entry consists of a number of strings. Here's an example file with only one entry (recipe): Name=Maple Quill...
1
by: Magnus | last post by:
allrite folks, got some questions here... 1) LAY-OUT OF REPORTS How is it possible to fundamentaly change the lay-out/form of a report in access? I dont really know it that "difficult", but...
50
by: Michael Mair | last post by:
Cheerio, I would appreciate opinions on the following: Given the task to read a _complete_ text file into a string: What is the "best" way to do it? Handling the buffer is not the problem...
2
by: Sabin Finateanu | last post by:
Hi I'm having problem reading a file from my program and I think it's from a procedure I'm using but I don't see where I'm going wrong. Here is the code: public bool AllowUsage() { ...
4
by: dale zhang | last post by:
Hi, I am trying to save and read an image from MS Access DB based on the following article: http://www.vbdotnetheaven.com/Code/Sept2003/2175.asp Right now, I saved images without any...
4
by: Amit Maheshwari | last post by:
I need to read text file having data either comma seperated or tab seperated or any custom seperator and convert into a DataSet in C# . I tried Microsoft Text Driver and Microsoft.Jet.OLEDB.4.0...
3
by: The Cool Giraffe | last post by:
Regarding the following code i have a problem. void read () { fstream file; ios::open_mode opMode = ios::in; file.open ("some.txt", opMode); char *ch = new char; vector <charv; while...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.