12 Replies - 1123 Views - Last Post: 15 July 2010 - 11:53 AM Rate Topic: -----

#1 avalanchez71  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 15-June 10

strings and char type arrays

Posted 14 July 2010 - 09:40 AM

Hello,
Is there something special you have to do to get a char type array to start at the beginning of a external file?
What i am trying to do is read in a string from an external file into a char type array and then display it on the screen. I have a function created to read the info but i am having problems with it grabbing the right info for each array. Here is what the input file looks like,
Samuel Spade         10 Automotive      22020.45
Annie Smith-Johnston  4 Appliances      25123.96
Dietrick Jones       15 Automotive      29450.88
John J. Jones, Jr.    8 Automotive      19555.55
Melissa Armstrong    12 Accounting      25945.66



Here is the code i have so far,
//List preprocessor directives
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <ctime>
#include <cmath>  //directive for math functions
using namespace std;

	const int NAME_SIZE = 21;
	const int DEPART_SIZE = 16;
	const int YEARS_SIZE = 3;
	const int SALARY_SIZE = 9;

//function prototypes
	int getAllData(char name[][NAME_SIZE], int& years, char depart[][DEPART_SIZE], double& salary);


int main() //function heading
{ 
	int actualnumber = 0;
	char name[100][NAME_SIZE];
	int years;
	char depart[100][DEPART_SIZE];
	double salary;

	getAllData(name, years, depart, salary);


	actualnumber = getAllData(name, years, depart, salary);

	int z = 0;
	while(z <= actualnumber)
		{
		cout << name[z] << endl;
		z++;
		}
	

	return 0;
}

int getAllData(char name[][NAME_SIZE], int& years, char depart[][DEPART_SIZE], double& salary)
{
	ifstream infile ("PJ811_personnel.txt");
	if (!infile) {							//unable to open file, display msg and quit
		cout << "Error: cannot open PJ811_personnel.txt file\n";

	}

	int count = 0;
	while(count < 100 && infile >> name[count])
	{
		infile.getline(name[count], sizeof(name[count]));

		infile >> years;
	
		infile.get(depart[count], DEPART_SIZE);
	
		infile >> salary;
		count++;
	}
	return count;
}

Now all i was outputing to the screen so far was just the name array, just to see if it is working but here is what i get,

 Spade         10 Au

Press any key to continue . . .


for some reason it is cutting off the first name and starting at the space between the first name and last name but its also not looping it looks like and displaying the whole list. I cant figure out how to get it to start at the First name, if it started at the first name then it would stop before it got to the "10".(at least i think it would)
I have tried puting a
infile >> ws;

before and after the infile for the name but nothing seems to work
Anyone have any ideas?

Is This A Good Question/Topic? 0
  • +

Replies To: strings and char type arrays

#2 Guest_guest*


Reputation:

Re: strings and char type arrays

Posted 14 July 2010 - 10:44 AM

Do your need to use C strings?

Storing each file line in a C++ string ( in an array, or vector, or list ... of strings ) may make you coding much easier.

There are plenty of examples here at DIC of reading a file, line by line, into an array (or vector) of strings ... this would be a good first step to get working ... then show back the data, line by line to the console screen.
Was This Post Helpful? 0

#3 avalanchez71  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 15-June 10

Re: strings and char type arrays

Posted 14 July 2010 - 10:53 AM

View Postguest, on 14 July 2010 - 09:44 AM, said:

Do your need to use C strings?

Storing each file line in a C++ string ( in an array, or vector, or list ... of strings ) may make you coding much easier.

There are plenty of examples here at DIC of reading a file, line by line, into an array (or vector) of strings ... this would be a good first step to get working ... then show back the data, line by line to the console screen.


Yes i am only suppose to use C-string variables and not C++.
But i was just trying to get it to work either way i could and worry about the C and C++ later.

It seems its the code is working somewhat just not displaying the correct info, its starting in the external file in the wrong spot.
Was This Post Helpful? 0
  • +
  • -

#4 Guest_guest*


Reputation:

Re: strings and char type arrays

Posted 14 July 2010 - 11:00 AM

Then you may like to write a function to grab a 'piece' of a line to 'parse' each line ... like this ...
(seems your in-data seems very regular )
char* newStr( char inStr[], int startIndex, int len )
{
   //
}


Was This Post Helpful? 0

#5 avalanchez71  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 15-June 10

Re: strings and char type arrays

Posted 14 July 2010 - 11:09 AM

View Postguest, on 14 July 2010 - 10:00 AM, said:

Then you may like to write a function to grab a 'piece' of a line to 'parse' each line ... like this ...
(seems your in-data seems very regular )
char* newStr( char inStr[], int startIndex, int len )
{
   //
}


I thought i was grabbing a piece of the line when i specified the length of the char name to 21 and the char depart to 16, is that not the case?
I thought by doing that it was only suppose to grab 20 charactures for name and 15 for depart.
Was This Post Helpful? 0
  • +
  • -

#6 avalanchez71  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 15-June 10

Re: strings and char type arrays

Posted 14 July 2010 - 11:16 AM

View Postavalanchez71, on 14 July 2010 - 10:09 AM, said:

View Postguest, on 14 July 2010 - 10:00 AM, said:

Then you may like to write a function to grab a 'piece' of a line to 'parse' each line ... like this ...
(seems your in-data seems very regular )
char* newStr( char inStr[], int startIndex, int len )
{
   //
}


I thought i was grabbing a piece of the line when i specified the length of the char name to 21 and the char depart to 16, is that not the case?
I thought by doing that it was only suppose to grab 20 charactures for name and 15 for depart.

well i got it to capture the whole name, the problem was in my while loop, it was
 	int count = 0;
	while(count < 100 && infile >> name[count])
	{
		infile.getline(name[count], sizeof(name[count]));

		infile >> years;
	
		infile.get(depart[count], DEPART_SIZE);
	
		infile >> salary;
		count++;
	}


but by changing the condition check from infile >> name[count] to !infile.eof() as in
	int count = 0;
	while(count < 100 && !infile.eof())
	{
		infile.getline(name[count], sizeof(name[count]));

		infile >> years;
	
		infile.get(depart[count], DEPART_SIZE);
	
		infile >> salary;
		count++;
	}


but its still only captures the first name in the list and doesnt display all of them
Was This Post Helpful? 0
  • +
  • -

#7 Guest_guest*


Reputation:

Re: strings and char type arrays

Posted 14 July 2010 - 11:22 AM

But first make sure you have all you file in an array big enough to hold all your C strings ...

in C ...
#define MAXLEN 80 /* over big for you ... */
#define MAXLINES 100 /* adjust to be big enough to hold all lines ...*/

/* function prototypes would come next ...*/

int main()
{
   char file_data[MAXLINES][MAXLEN+1];

   // ...

   return 0;
}

Was This Post Helpful? 0

#8 avalanchez71  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 15-June 10

Re: strings and char type arrays

Posted 14 July 2010 - 11:30 AM

View Postguest, on 14 July 2010 - 10:22 AM, said:

But first make sure you have all you file in an array big enough to hold all your C strings ...

in C ...
#define MAXLEN 80 /* over big for you ... */
#define MAXLINES 100 /* adjust to be big enough to hold all lines ...*/

/* function prototypes would come next ...*/

int main()
{
   char file_data[MAXLINES][MAXLEN+1];

   // ...

   return 0;
}

i thought i did when i declared the variable as in
char name[100][NAME_SIZE];


isn't that what the 100 does?
Was This Post Helpful? 0
  • +
  • -

#9 avalanchez71  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 15-June 10

Re: strings and char type arrays

Posted 14 July 2010 - 11:52 AM

anyone know what the difference really is between the C version and the C++ version of string variables?
Was This Post Helpful? 0
  • +
  • -

#10 Guest_guest*


Reputation:

Re: strings and char type arrays

Posted 14 July 2010 - 12:18 PM

View Postavalanchez71, on 14 July 2010 - 10:52 AM, said:

anyone know what the difference really is between the C version and the C++ version of string variables?


Sorry for the previous rushed answers ... There is MUCH on the net re. C vs C++ strings

Just 2 quick differences ...

C strings are '\0' terminated arrays of char ... you need to manage the array memory size yourself

C++ strings are C++ objects that may or may not be '\0' terminated but their memory management is automatic

(There is MUCH more ... that makes C++ strings, often, MUCH preferred.)

Must run now ... There are MANY here at DIC that can help you.

Is your program to be ALL in C ... or ALL in C++ except to use only C strings?
Was This Post Helpful? 0

#11 avalanchez71  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 15-June 10

Re: strings and char type arrays

Posted 14 July 2010 - 12:48 PM

View Postguest, on 14 July 2010 - 11:18 AM, said:

View Postavalanchez71, on 14 July 2010 - 10:52 AM, said:

anyone know what the difference really is between the C version and the C++ version of string variables?


Sorry for the previous rushed answers ... There is MUCH on the net re. C vs C++ strings

Just 2 quick differences ...

C strings are '\0' terminated arrays of char ... you need to manage the array memory size yourself

C++ strings are C++ objects that may or may not be '\0' terminated but their memory management is automatic

(There is MUCH more ... that makes C++ strings, often, MUCH preferred.)

Must run now ... There are MANY here at DIC that can help you.

Is your program to be ALL in C ... or ALL in C++ except to use only C strings?


i believe everything is in C++ expect the strings and they are to be in C. I am making headway on it, i believe i got it to read everything but i was to have 4 different inputs.
First one being a c-string for the name of he person,
the second being an interger for the year,
the third a c-string again for the depart,
and the fourth i believe a double for the salary.
I can get it to work if i make everything c-string and not an int or a double and i am not sure why yet.
Was This Post Helpful? 0
  • +
  • -

#12 Guest_guest*


Reputation:

Re: strings and char type arrays

Posted 15 July 2010 - 11:31 AM

View Postavalanchez71, on 14 July 2010 - 11:48 AM, said:

... i believe everything is in C++ expect the strings and they are to be in C. I am making headway on it, i believe i got it to read everything but i was to have 4 different inputs.
First one being a c-string for the name of he person,
the second being an interger for the year,
the third a c-string again for the depart,
and the fourth i believe a double for the salary.
I can get it to work if i make everything c-string and not an int or a double and i am not sure why yet.


Then ... here is a common and easy approach that first reads every line of your data file into an array of strings ...

then you can process that array of strings as you wish ... by parsing (getting each field in) each line (a string) of that (structured) data ... and then processing that field as you wish ...

// processData.cpp // problem spec's to use only C strings (not C++ strings)

// data.txt
/*
0                    2  2              3       4
0123456789012345678901234567890123456789012345678

Samuel Spade         10 Automotive      22020.45
Annie Smith-Johnston  4 Appliances      25123.96
Dietrick Jones       15 Automotive      29450.88
John J. Jones, Jr.    8 Automotive      19555.55
Melissa Armstrong    12 Accounting      25945.66

*/


#include <iostream>
#include <iomanip> // re setw(..), setprecision(..), fixed
#include <fstream>
#include <cstring>
#include <cstdlib> // re. atoi(..) and atof(..)
using namespace std;

const int MAXLEN = 48; // each line of file data is padded to 48 char's
const int MAXSIZE = 100;

// function prototypes ...
int getAllData( char myStore[][MAXLEN+1] ); // leave room for terminal '\0' char
char* getSubStr( char str[], int startIndex, int len, char buffer[] );


int main()
{
    char myStore[MAXSIZE][MAXLEN+1]; // an array to hold upto MAXSIZE CString's

    int size = getAllData( myStore );
    
    // show all lines in myStore ...
        
    for( int j = 0; j < size; ++j )
         cout << myStore[j] << endl;
    cout << "\nPress 'Enter' to continue ..." << flush;
    cin.get();

    // show all lines in myStore ... field by field
    
    char buf[MAXLEN+1];
    for( int j = 0; j < size; ++j )
    {
         cout << getSubStr( myStore[j], 0, 20, buf );
         cout << getSubStr( myStore[j], 20, 3, buf ) << " ";
         cout << getSubStr( myStore[j], 24, 15, buf );
         cout << getSubStr( myStore[j], 39, 9, buf ) << endl;
    }                               
    cout << "\nPress 'Enter' to continue ..." << flush;
    cin.get();
    
    // show all lines in myStore ... field by field ... extracting numbers    

    cout << fixed << setprecision(2);
    for( int j = 0; j < size; ++j )
    {
         cout << getSubStr( myStore[j], 0, 20, buf );
         cout << setw(3) << atoi( getSubStr( myStore[j], 20, 3, buf ) ) << " ";
         cout << getSubStr( myStore[j], 24, 15, buf );
         cout << setw(9) << atof( getSubStr( myStore[j], 39, 9, buf ) ) << endl;
    }                               
    cout << "\nPress 'Enter' to exit ..." << flush;
    cin.get();
}


int getAllData( char myStore[][MAXLEN+1] )
{
    int i = 0;   
    ifstream fin( "data.txt" );
    while( i < MAXSIZE && fin.getline( myStore[i], MAXLEN+1 ) ) ++i;
    return i;
}

char* getSubStr( char str[], int startIndex, int len, char buffer[] )
{
      strncpy( buffer, str+startIndex, len );           
      buffer[len] = 0; // '\0' termijnate ...
      return buffer;
}




Or ... (and this may help to show that a 2D array in C/C++ is an array of arrays) ...


// processData2.cpp // problem spec's to use only C strings (not C++ strings)

// data.txt
/*
0                    2  2              3       4
0123456789012345678901234567890123456789012345678

Samuel Spade         10 Automotive      22020.45
Annie Smith-Johnston  4 Appliances      25123.96
Dietrick Jones       15 Automotive      29450.88
John J. Jones, Jr.    8 Automotive      19555.55
Melissa Armstrong    12 Accounting      25945.66

*/


#include <iostream>
#include <iomanip> // re setw(..), setprecision(..), fixed
#include <fstream>
#include <cstring>
#include <cstdlib> // re. atoi(..) and atof(..)
using namespace std;

const int MAXLEN = 48; // each line of file data is padded to 48 char's
const int MAXSIZE = 100;

// Note: here CStrings 'are arrays-of/pointers-to' ... 49 char's of memory
typedef char CString[MAXLEN+1]; // define CString to hold (upto) 48 char's + '\0'

// function prototypes ...
int getAllData( CString myStore[MAXLEN+1] ); // leave room for terminal '\0' char
CString& getSubStr( const CString& str, int startIndex, int len, CString& buffer );


int main()
{
    // this may help to show that a 2D array in C/C++ is an array of arrays ...
    CString myStore[MAXSIZE]; // an array to hold upto MAXSIZE CString's

    int size = getAllData( myStore );
    
    // show all lines in myStore ...
        
    for( int j = 0; j < size; ++j )
         cout << myStore[j] << endl;
    cout << "\nPress 'Enter' to continue ..." << flush;
    cin.get();

    // show all lines in myStore ... field by field
    
    CString buf;
    for( int j = 0; j < size; ++j )
    {
         cout << getSubStr( myStore[j], 0, 20, buf );
         cout << getSubStr( myStore[j], 20, 3, buf ) << " ";
         cout << getSubStr( myStore[j], 24, 15, buf );
         cout << getSubStr( myStore[j], 39, 9, buf ) << endl;
    }                               
    cout << "\nPress 'Enter' to continue ..." << flush;
    cin.get();
    
    // show all lines in myStore ... field by field ... extracting numbers    

    cout << fixed << setprecision(2);
    for( int j = 0; j < size; ++j )
    {
         cout << getSubStr( myStore[j], 0, 20, buf );
         cout << setw(3) << atoi( getSubStr( myStore[j], 20, 3, buf ) ) << " ";
         cout << getSubStr( myStore[j], 24, 15, buf );
         cout << setw(9) << atof( getSubStr( myStore[j], 39, 9, buf ) ) << endl;
    }                               
    cout << "\nPress 'Enter' to exit ..." << flush;
    cin.get();
}


int getAllData( char myStore[][MAXLEN+1] )
{
    int i = 0;   
    ifstream fin( "data.txt" );
    while( i < MAXSIZE && fin.getline( myStore[i], MAXLEN+1 ) ) ++i;
    return i;
}

CString& getSubStr( const CString& str, int startIndex, int len, CString& buffer )
{
      strncpy( buffer, str+startIndex, len );           
      buffer[len] = 0; // '\0' termijnate ...
      return buffer;
}


Was This Post Helpful? 0

#13 Guest_allCString*


Reputation:

Re: strings and char type arrays

Posted 15 July 2010 - 11:53 AM

Or ... using all CStrings ...

// processData3.cpp // problem spec's to use only C strings (not C++ strings)

// data.txt
/*
0                    2  2              3       4
0123456789012345678901234567890123456789012345678

Samuel Spade         10 Automotive      22020.45
Annie Smith-Johnston  4 Appliances      25123.96
Dietrick Jones       15 Automotive      29450.88
John J. Jones, Jr.    8 Automotive      19555.55
Melissa Armstrong    12 Accounting      25945.66

*/


#include <iostream>
#include <iomanip> // re setw(..), setprecision(..), fixed
#include <fstream>
#include <cstring>
#include <cstdlib> // re. atoi(..) and atof(..)
using namespace std;

const int MAXLEN = 48; // each line of file data is padded to 48 char's
const int MAXSIZE = 100;

// Note: here CStrings 'are arrays-of/pointers-to' ... 49 char's of memory
typedef char CString[MAXLEN+1]; // define CString to hold (upto) 48 char's + '\0'

// function prototypes ...
int getAllData( CString myStore[] ); 
CString& getSubStr( const CString& str, int startIndex, int len, CString& buffer );


int main()
{
    // this may help to show that a 2D array in C/C++ is an array of arrays ...
    CString myStore[MAXSIZE]; // an array to hold upto MAXSIZE CString's

    int size = getAllData( myStore );
    
    // show all lines in myStore ...
        
    for( int j = 0; j < size; ++j )
         cout << myStore[j] << endl;
    cout << "\nPress 'Enter' to continue ..." << flush;
    cin.get();

    // show all lines in myStore ... field by field
    
    CString buf;
    for( int j = 0; j < size; ++j )
    {
         cout << getSubStr( myStore[j], 0, 20, buf );
         cout << getSubStr( myStore[j], 20, 3, buf ) << " ";
         cout << getSubStr( myStore[j], 24, 15, buf );
         cout << getSubStr( myStore[j], 39, 9, buf ) << endl;
    }                               
    cout << "\nPress 'Enter' to continue ..." << flush;
    cin.get();
    
    // show all lines in myStore ... field by field ... extracting numbers    

    cout << fixed << setprecision(2);
    for( int j = 0; j < size; ++j )
    {
         cout << getSubStr( myStore[j], 0, 20, buf );
         cout << setw(3) << atoi( getSubStr( myStore[j], 20, 3, buf ) ) << " ";
         cout << getSubStr( myStore[j], 24, 15, buf );
         cout << setw(9) << atof( getSubStr( myStore[j], 39, 9, buf ) ) << endl;
    }                               
    cout << "\nPress 'Enter' to exit ..." << flush;
    cin.get();
}


int getAllData( CString myStore[] )
{
    int i = 0;   
    ifstream fin( "data.txt" );
    while( i < MAXSIZE && fin.getline( myStore[i], MAXLEN+1 ) ) ++i;
    return i;
}

CString& getSubStr( const CString& str, int startIndex, int len, CString& buffer )
{
      strncpy( buffer, str+startIndex, len );           
      buffer[len] = 0; // '\0' termijnate ...
      return buffer;
}


Was This Post Helpful? 0

Page 1 of 1