Strings to an array

Hello,
I have to read in a .txt file with 5 lines of text and I cannot find an tutorial with the necessary functionality I'm looking for. I am aware I have to read the string into an array but I'm confused on how to do it, and how to display it. All comments are gratefully appreciated.

This is what is in the text file :

1
2
3
4
5
Tom Smith,1 Main Street,Rochester,New York,14623
Billy Bob Thorton,2304 Cameron Way,Nashville,Tennessee,45042-5402
Bruce Eckel,561 Chillington Lane,San Francisco,California,950333
Lee Gaddis,4203 Mountain View Dr.,Buford,Arkansas,47203-564
Jimmy Jo Jones,169 Maplewood Street,Land-of-Lakes,Minnesota,67209


This is what I have so far, please explain as detailed as possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  
#include <iostream>
#include <string>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <iomanip>

using namespace std;

int main ()
{

	//put your code after this line
    string s = "Tom Smith,1 Main Street,Rochester,New York,14623";

    // printing original string
    cout <<  "Original string <" << s << ">" << endl;

    // variables to find the commas.
    string szInput[5];
    int locOfCma1 = s.find( ',' );
    int locOfCma2 = s.find(',', locOfCma1+1);
    int locOfCma3 = s.find(',', locOfCma2+1);
    int locOfCma4 = s.find(',', locOfCma3+1);


    string name =  s.substr(0,locOfCma1);
    string address = s.substr(locOfCma1 + 1, locOfCma2 - locOfCma1 - 1);
    string town = s.substr(locOfCma2 + 1, locOfCma3 - locOfCma1 - 1);
    string zip = s.substr(locOfCma4 + 1);

    //replaces comma after New York.
    town.replace(18,1, " ");
    // inserts space after Rochester,
    town.insert(10, " ");

    // Displaying address line
    cout << name << endl;
    cout << address << endl;
    cout << town << endl;
    cout << zip << endl;



    // Error checking for Zip
    if (zip.length() == 5 || zip.length() == 10)
    {
        cout << "Valid zip code" << endl;
    }
    else
    {
        cout << "Zip code is invalid" << endl;
    }

    return 0;
} //end main


   
Last edited on
Topic archived. No new replies allowed.