-1

this is my code below, the output is numbers relating to a grade. I want to be able to make each line of the string a variable such as int grade1 and so on, so that I can display certain variables and not the whole string for example cout << grade1 << grade2 << endl;

using namespace std;
int main()
{

    string line;
    ifstream myfile("Data.csv"); //opening the CVS file
    if (myfile.is_open())
    {
        while (getline(myfile, line)) //used to read each line of the file
        {

            string str(line); //making the file a string

            char chars[] = ",abcdefghijklmnopqrstuvwxyzN;:/"; //Characters to be removed

            for (unsigned int i = 0; i < strlen(chars); ++i)
            {
                str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());
            }

            str.replace(0, 9, " ");

            cout << str << endl;
        }

        myfile.close(); //closes the file

    }
    else
        cout << "pathway to file can't be found" << '\n'; //error message to display if file location cant be found. 

    cin.get();

    return 0;
}
dkg
  • 1,775
  • 14
  • 34
  • Please format your code. Right now it is hard to read. – Werner Henze Feb 03 '15 at 12:23
  • 2
    You have mismatched braces. You say `using namespace std` then still use `std::` scope everywhere. Clean up your post so we can see what you are talking about, and please explain your question more clearly. – Cory Kramer Feb 03 '15 at 12:24
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](http://stackoverflow.com/help/how-to-ask) page for help clarifying this question. – utnapistim Feb 03 '15 at 12:35
  • I want to make the string into variables not sure how else you want it worded – user2981019 Feb 03 '15 at 12:38
  • You should have a look at STL. Use containers – Dimitri Mockelyn Feb 03 '15 at 12:40
  • @user2981019, it sounds like you are looking for parsing the content of the files. Have a look at std::istringstream and examples that use it in conjunction with std::ifstream (like [this one](http://stackoverflow.com/a/7868998/186997) - reading two integers from each line). – utnapistim Feb 03 '15 at 12:52

1 Answers1

1

The question and especially the code is rather difficult to comprehend, but I understood that you want to create string variables for each line of the file.

A simple way is to loop through the file line-by-line, store the line into a string variable and then push that variable to a vector.

std::string line;
std::vector<std::string> lines;

while (getline(myfile, line))
{
    lines.push_back(line);
}
OwlOCR
  • 1,127
  • 11
  • 22