将 ifstream 文件和每一行读取到数组中

read ifstream file and each line into a array

本文关键字:一行 读取 数组 文件 ifstream      更新时间:2023-10-16

我希望有人能够帮助我,或者至少理解我想要实现的目标。 我试着在网上搜索这个,但我没有找到答案,或者至少不明白别人做了什么。

因此,我试图将文件.txt的每一行读取到数组中。 例如,我的文件.txt包含:

3
labas 
ka tu
nu tai davai

(仅举个例子(

我想把每一行都放进我的

string sentenses[CMax]; 

(CMax 设置为 10000(

经过几个小时的搜索网络和修补自己,我最终得到了:

ifstream KC;
KC.open(langPicked.c_str());
KC >> m;
for (int o = 0; o < m; o++) {
KC.getline(sentenses[o], 255); 
if(KC) cout << sentenses[o] << endl;
}
KC.close();

但是,令人惊讶的是,它不起作用。

基本上,我想要实现的是,来自 KC 的每一行都将添加到>> sentenses[o] 数组中,这样我就可以像我键入以下内容来计算出我想要的任何行

cout << sentenses[2] << endl;

它将输出 2 行:

卡图

弹出的错误:

D:\Lith\Codeblocks\uzd\Skaiciuokle 2.0\main.cpp|88|error: 没有匹配函数来调用 'std::basic_ifstream::getline(std::__cxx11::string&, int('|

注意: 我发布的代码可能,并且在某种程度上是错误的形状或形式。我刚刚开始尝试自己学习 c++。如果您了解我想要做什么,请随时用适合我情况的自己编写的代码来回答。提前谢谢你

看看这个伪代码:

string filename; //load the filename
cout << "Give the name of the file:n";
cin >> filename;
cout << endl; 
ifstream file;
string txt = ".txt";
filename.append(txt);  //append .txt to the filename
file.open(filename);   //open this file
if(file.is_open()) {
const int CMax = 10000;
string senteces[CMax];
int o = 0;
while (getline(file, senteces[o])) 
++o;
cout << senteces[2] << endl; //it will print "ka tu"
cout << senteces[0] << endl; //it will print "3"
}

谢谢Rustyx

解决方案是更改Getline。

对于任何1感兴趣。此代码正在工作:

ifstream KC;
KC.open(langPicked.c_str());
KC >> m;
for (int o = 0; o < m; o++) {
getline(KC, sentenses[o]);
}
KC.close();

附言idk如何将rustyx的答案附加到"已解决"部分,所以我发表了自己的评论。不好意思