简体   繁体   中英

error reading data from input file to array

The input file contains 14 state initials (TN,CA,NB,FL,etc..) that is to be rad into the array. The code below clears compiler but when i tell the program the filename it shoots out a bunch of blank spaces with two spaces containing some fuzz and a third contain a '@' symbol. i assume the problem is with my function not entirely sure what specifically though any help greatly appreciated!

input file set up with state initials one on top of the other:

TN PA KY MN CA and so on

void readstate( ifstream& input, string []);
int main()
{
   string stateInitials[14];
   char filename[256];
   ifstream input;

   cout << "Enter file name: ";
   cin >> filename;

   input.open( filename );

   if ( input.fail())
   {
      cout << " file open fail" << endl;
   }
   readstate ( input, stateInitials); 

   input.close();

   return (0);
}

void readstate ( ifstream& input, string stateInitials[])
{
   int count;  

   for ( count = 0; count <= MAX_ENTRIES; count++)
   {
       input >> stateInitials[count];
       cout << stateInitials[count] << endl;
   }
}   

You are treating a character array as though it were a string array. While you can hack put the strings next to each other inside the same char array, that is not the standard way it is done. Here is a modified version of your code, which creates one char[] to hold each initial.

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <string.h>



#define MAX_ENTRIES 14

using namespace std;
void readstate( ifstream& input, char* []);
int main()
{
   char** stateInitials = new char*[14];
   char filename[256];
   ifstream input;

   cout << "Enter file name: ";
   cin >> filename;

   input.open( filename );

   if ( input.fail())
   {
      cout << " file open fail" << endl;
   }
   readstate ( input, stateInitials); 

   // After you are done, you should clean up
   for ( int i = 0; i <= MAX_ENTRIES; i++) delete stateInitials[i];
   delete stateInitials;
   return (0);
}

void readstate ( ifstream& input, char* stateInitials[])
{
   int count;  

   string temp_buf;
   for ( count = 0; count <= MAX_ENTRIES; count++)
   {
       stateInitials[count] = new char[3];

       input >> temp_buf;
       memcpy(stateInitials[count], temp_buf.c_str(), 3);
       cout << stateInitials[count] << endl;
   }
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM