C++ String Array, Loading lines of text from file
I have a problem. When I try to load a file into a string array nothing shows.
Firstly I have a file that on one line has a username and on the second has a password. I haven't finished the code but when I try to display what is in the array nothing displays. I would love for this to work.Any suggestions?
users.txt
user1
password
user2
password
user3
password
C++ Code
void loadusers()
{
string t;
string line;
int lineCount=0;
int lineCount2=0;
int lineCount3=0;
ifstream d_file("data/users.txt");
while(getline(d_file, t, '\n'))
++lineCount;
cout << "开发者_如何学PythonThe number of lines in the file is " << lineCount << endl;
string users[lineCount];
while (lineCount2!=lineCount)
{
getline(d_file,line);
users[lineCount2] = line;
lineCount2++;
}
while (lineCount3!=lineCount)
{
cout << lineCount3 << " " << users[lineCount3] << endl;
lineCount3++;
}
d_file.close();
}
Use a std::vector<std::string>
:
std::ifstream the_file("file.txt");
std::vector<std::string> lines;
std::string current_line;
while (std::getline(the_file, current_line))
lines.push_back(current_line);
You cannot create arrays in C++ with runtime values, the size of the array needs to be known on compile time. To solve this you may use a vector for this ( std::vector )
You need the following include:
#include <vector>
And the implementation for load_users would look like this:
void load_users() {
std::ifstream d_file('data/users.txt');
std::string line;
std::vector<std::string> user_vec;
while( std::getline( d_file, line ) ) {
user_vec.push_back( line );
}
// To keep it simple we use the index operator interface:
std::size_t line_count = user_vec.size();
for( std::size_t i = 0; i < line_count; ++i ) {
std::cout << i << " " << user_vec[i] << std::endl;
}
// d_file closes automatically if the function is left
}
I guess you will find your best answer using istringstream.
精彩评论