473,799 Members | 3,149 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do i read a file in from a vector?

7 New Member
So my program works all right, but I can't read my information from a file into my vector, what am I doing wrong?

Expand|Select|Wrap|Line Numbers
  1. vector<char> grades;
  2.     grades.push_back ('A');
  3.     grades.push_back ('B');
  4.     grades.push_back ('C');
  5.     grades.push_back ('D');
  6.     grades.push_back ('E');
  7.  
  8.  
  9.  
  10.     // declare a place to hold scores read from a file 
  11.     //int scores[10]={0};
  12.     vector<int> scores ;
  13.  
  14.     // declare the stream object and open the file
  15.     ifstream theDataFile;
  16.     theDataFile.open("c:\\scores.txt");
  17.     if (theDataFile.rdstate() !=0)
  18.     {
  19.         cout << "\nError opening file.";
  20.         exit(1);    
  21.     }
  22.     else
  23.         cout <<"\nThe File opened correctly";
  24.     // read the scores into the array
  25.     int i = 0;
  26.     int aScore = 0;
  27.     int index = 0;
  28.     while(!theDataFile.eof( ))
  29.     {
  30.         theDataFile >> aScore;
  31.         if(!theDataFile.good( )) // the read failed ...
  32.         {
  33.             if (!theDataFile.eof( )) // and it was not an eof condition
  34.             {
  35.                 cout << "\nError reading file.";
  36.                 exit(1);
  37.             }
  38.             break; // it was an eof, so break out of the loop
  39.         }
  40.          //scores[index++] = aScore;
  41.         scores.push_back(aScore);
  42.     }
  43.  
  44.     // print out the values just read and give each a grade
  45.     for (int i = 0; i < index; i++) 
  46.     {
  47.  
  48.         cout << scores.size () ;
  49.         if (scores[i] < 61)
  50.             cout << grades [4];  // grade is an 'E'
  51.         else if (scores[i] < 71)
  52.             cout << grades [3];  // grade is a 'D'
  53.         else if (scores[i]  < 81)
  54.             cout << grades [2];  // grade is a 'C'
  55.         else if (scores [i] < 91)
  56.             cout << grades [1];  // grade is a 'B'
  57.         else
  58.             cout << grades [0];  // grade is an 'A'
  59.         cout << endl;
  60.     }
  61.  
  62.     system("PAUSE");
  63.     return 0;
Dec 14 '08 #1
2 2052
manontheedge
175 New Member
to read in a vector from a file you can't read directly into the vector, you need to do something like ...

Expand|Select|Wrap|Line Numbers
  1.  
  2. vector<char> numbers;
  3. char temp;
  4.  
  5. // then inside of your loop ...
  6. cin >> temp;
  7. number.push_back( temp );
  8.  
  9.  

... that's basically the format it has to be done in. It's the same for any data type, i.e. integers, characters, strings, ...


sorry, I re-read your post after I posted an this appears to be pretty much what you're doing, ... I'd say to try to take out ALL of the error checking stuff you have, and see if it reads anything with none of the error checking, then if it does, you know there's a problem there. If that's NOT the problem, then make sure the temporary character that your pushing onto the vector has SOMETHING in it each time.
Dec 15 '08 #2
Ganon11
3,652 Recognized Expert Specialist
Since you've commented out the faulty line scores[index++] = aScore, index is no longer getting updated, so your final loop will not work anymore. Try getting scores.size() into a variable and looping based on that instead of index.
Dec 15 '08 #3

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

Similar topics

3
2672
by: John Flynn | last post by:
hi, having problems reading from and writing back to the same file. basically, i want to read lines of text from a file and reverse them and write them back to the same file.. it has to replace the text its reversing eg.
2
22834
by: hvaisane | last post by:
Valgrind says ==11604== Invalid read of size 4 ==11604== at 0x8048ABB: main (foo.cc:36) ==11604== Address 0x1B92415C is 4 bytes inside a block of size 8 free'd ==11604== at 0x1B90514F: operator delete(void*) (vg_replace_malloc.c:156) ==11604== by 0x804A1BA: __gnu_cxx::new_allocator<Foo>::deallocate(Foo*, unsigned) (new_allocator.h:86) ==11604== by 0x8049C08: std::_Vector_base<Foo, std::allocator<Foo> >::_M_deallocate(Foo*,...
2
6717
by: kak3012 | last post by:
Hi, I have a text file I will read it and write out binary. The file includes 256 coloums. I use while (infile.good()) { infile.getline (buffer,2200);
4
1864
by: pisscot | last post by:
Lind Apr 13, 6:32 am show options Newsgroups: comp.lang.c From: piss...@gmail.com (Lind) - Find messages by this author Date: 13 Apr 2005 06:32:15 -0700 Local: Wed,Apr 13 2005 6:32 am Subject: how to read it out using c++ Reply | Reply to Author | Forward | Print | Individual Message | Show original | Remove | Report Abuse
4
8048
by: James Aguilar | last post by:
Hey all, I'm working on an encoding scheme where I am running into a problem with reading a file off a stream. Looking at the binary encoding of the file (using a simple hex editor), there is no problem, and the whole file is there. However, when I try to read it from cin, at certain times, cin stops reading. I cannot force cin to go around the bad character, nor, indeed, do I know what the bad character is. I am including code at...
9
6828
by: sshock | last post by:
Hi all, I want to read from a file into a vector<unsigned char>. Right now my code looks like this: FILE* f = fopen( "datafile", "rb" ); enum { SIZE = 100 }; vector<unsigned char> buf(SIZE); fread(&buf, 1, SIZE, f);
2
5519
by: RyanS09 | last post by:
Hi- I have read many posts with specific applications of reading in text files into arrays, however I have not been able to successfully modify any for my application. I want to take a text file filled with a tab delimited list of 10 columns (floats) and read it into a 2D array. The length of the columns are all the same, however this will be variable from text file to text file. Any help (starter code or where to read) would be much...
6
5719
by: arnuld | last post by:
This works fine, I welcome any views/advices/coding-practices :) /* C++ Primer - 4/e * * Exercise 8.9 * STATEMENT: * write a program to store each line from a file into a * vector<string>. Now, use istringstream to read read each line * from the vector a word at a time.
9
3471
by: Matrixinline | last post by:
Hi All, Here is the problem char* memblock; std::ifstream file(sFileName, ios::in|ios::binary); if (file.is_open()) { size = file.tellg();
0
9541
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
10484
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...
0
10027
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
9072
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
6805
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
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
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.