LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Read and save from a .txt - C++ (http://www.linuxquestions.org/questions/programming-9/read-and-save-from-a-txt-c-715133/)

inpanzinator 03-28-2009 12:59 PM

Read and save from a .txt - C++
 
Hey. I need to read from a file called ranking.txt the name of the players and the respective score. The file is something like this:

Code:

24145 John Burt
12442 Kate Blair
1244 Jacob

Then, I need to save the data into a vector, best_scores, defined by a data struct.

Code:

struct Score {
string name;
int score;
};

vector<Score> best_scores;

Can you help me?


Btw, I did this:

Code:

#include <iostream>
#include <fstream>
#include<string>
#include<vector>
#include <sstream>

using namespace std;

struct Score{
        string name;
        int score;
}a, b, c, d, e, f, g, h, i, j;

vector<Score> best_scores;


int main () {
  char c, str[256] = "ranking.txt";
  ifstream is;

  is.open (str);        // open file
  string b;
  while (is.good())    // loop while extraction from file is possible
  {
    c = is.get(); // get character from file
    if (isdigit(c))
    {
            b += c;
    }
    else
            if (isalpha(c))
            {
                    a.name += c;
            }
    stringstream s(b);
    s >> a.score;

  }
  cout << a.score<< endl;
  cout << a.name << endl;
  is.close();
  return 0;


}


AceofSpades19 03-28-2009 02:05 PM

Why are you using char arrays instead of std::string?

David1357 03-28-2009 03:21 PM

Quote:

Originally Posted by inpanzinator (Post 3490774)
Can you help me?

That looks suspiciously like homework.


All times are GMT -5. The time now is 10:50 AM.