2010-10-10 9 views
2

我遇到问题。当我尝试将文件加载到字符串数组中时,什么也没有显示。
首先,我有一个文件,在一行上有一个用户名,第二个有密码。
我还没有完成代码,但是当我尝试显示数组中什么都没有显示。
我很喜欢这个工作。C++ String Array,从文件加载文本行

有什么建议吗?

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(); 
} 
+0

谢谢大家的输入!希望我会用这些新获得的知识来解决我的问题。这需要我花几天的时间来弄清楚如何解决它。 – Luke 2010-10-10 20:31:36

回答

3

不能创建在C++与运行时的值的阵列,所需要的阵列的大小上编译时是已知的。为了解决这个问题,你可以使用一个向量这个(标准::向量)

您需要以下包括: #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 
} 
+0

如何使用矢量,在这种情况下? (我只知道C++的一些功能) – Luke 2010-10-10 20:10:43

4

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

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

+0

istringstream默认会在每个空白处停止。如果你有一个包含空格的用户名,你会被拧紧;-) – Vinzenz 2010-10-10 21:00:50