-
Arrays and File I/O
Hello, I am totally new to arrays. I'm posting this in the C++ forum because my game is a mediocre console window and I guess that the solution to my array problem is simple. So, I wrote a simple "Guess the number" game and recently implemented a mediocre highscore system.
Here's how it works:
When the player gets a highscore, the program creates a text file that contains a string composed of the player's score and of the player's name (Format example : 06John). Before starting a new game, the program reads the previously created file with the use of arrays, and shows the player's name and score.
Here's a snippet of my code showing the reading part:
Code:
char highscore[50];
ifstream read ("Highscore.txt");
read >> highscore;
cout << "Highscore: " << highscore[2] << " in ";
cout << highscore[0] << highscore[1] << " turns." << endl;
Here's the text file:
And output:
Code:
Highscore: J in 06 turns.
As you can see, the problem is that currently the player's name is one letter. Is there a way to read (with arrays) until the end of the player's name, starting from slot 2?
I'm sure the solution is obvious.
Thanks.
-
unsigned MAX = 256;
char name[MAX + 1];
read.getline(name, MAX);
-
In C++, you use string types to read in strings. A string type automatically adjusts it's size to handle whatever length string you need to read into it:
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "hello";
cout<<str<<endl;
str = "hello world";
cout<<str<<endl;
return 0;
}
A string type can be treated like an array, with the first character at index 0 and the next character at index 1, etc. You can use the string function substr() to extract portions of the string you are interested in:
Code:
string str = "06John";
cout<<str.substr(0,2)<<endl;
cout<<str.substr(2)<<endl;
-
Code:
char highscore[50];
ifstream read ("Highscore.txt");
read >> highscore;
cout << "Highscore: " << &highscore[2] << " in ";
cout << highscore[0] << highscore[1] << " turns." << endl;