gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:49:39 25 4
gpt4 key购买 nike

我有一个问题。当我尝试将文件加载到字符串数组时,没有任何显示。
首先,我有一个文件,第一行有用户名,第二行有密码。
我还没有完成代码,但是当我尝试显示数组中的内容时,什么也没有显示。
我希望它能起作用。

有什么建议吗?

用户.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++ 字符串数组,从文件中加载文本行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3901977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com