C++字符串数组,从文件中加载文本行
Posted
技术标签:
【中文标题】C++字符串数组,从文件中加载文本行【英文标题】:C++ String Array, Loading lines of text from file 【发布时间】:2010-10-10 20:05:30 【问题描述】:我有问题。当我尝试将文件加载到字符串数组中时,没有任何显示。 首先,我有一个文件,其中一行有用户名,第二行有密码。 我还没有完成代码,但是当我尝试显示数组中的内容时,什么都没有显示。 我希望它能够正常工作。
有什么建议吗?
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();
【问题讨论】:
谢谢你们的意见!希望我能用这些新获得的知识来修复我的应用程序。这需要我几天时间才能弄清楚如何解决它。 【参考方案1】:使用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);
【讨论】:
【参考方案2】:您不能在 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
【讨论】:
在这种情况下如何使用向量? (我只知道一点C++的功能)【参考方案3】:我猜您会使用 istringstream 找到最佳答案。
【讨论】:
istringstream 默认会在每个空格处停止。如果你有一个包含空格的用户名,你会被搞砸的;-)以上是关于C++字符串数组,从文件中加载文本行的主要内容,如果未能解决你的问题,请参考以下文章
C 语言文件操作 ( 配置文件读写 | 写出或更新配置文件 | 逐行遍历文件文本数据 | 获取文件中的文本行 | 查询文本行数据 | 追加文件数据 | 使用占位符方式拼接字符串 )