繁体   English   中英

C ++字符串数组,从文件加载文本行

[英]C++ String Array, Loading lines of text from file

我有个问题。 当我尝试将文件加载到字符串数组时,没有任何显示。
首先,我有一个文件,在一行上有一个用户名,第二行有一个密码。
我还没有完成代码,但是当我尝试显示数组中没有显示的内容时。
我很乐意为此工作。

有什么建议么?

users.txt

user1
password
user2
password
user3
password

C ++代码

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 << "The 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();
}

使用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);

您无法使用运行时值在C ++中创建数组,需要在编译时知道数组的大小。 要解决这个问题,你可以使用一个向量(std :: vector)

您需要以下内容: #include <vector>

load_users的实现如下所示:

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
}

我想你会找到使用istringstream的最佳答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM