如何从文件中读取文本行并将它们放入数组中

时间:2012-07-18 16:36:26

标签: c++ arrays

我创建了一个文本文件love.txt

i love you
you love me

如何将它们存储到单独的数组中,即line1line2,然后在控制台中显示它们?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
  string line1[30];
  string line2[30];
  ifstream myfile("love.txt");
  int a = 0;
  int b = 0;
  if(!myfile) 
  {
    cout<<"Error opening output file"<<endl;
    system("pause");
    return -1;
  }
  while(!myfile.eof())
  {
    getline(myfile,line1[a],' ');
    cout<<"1."<<line1[a]<<"\n";
    getline(myfile,line2[b],' ');
    cout<<"2."<<line2[b]<<"\n";
  }
}

3 个答案:

答案 0 :(得分:5)

尝试在getline()个函数中将最后一个参数指定为'\ n'

getline(myfile, line1[a], '\n');

而不是

getline(myfile, line1[a], ' ');

答案 1 :(得分:2)

您可以将字符串视为字符数组,因此您只需要一个字符串数组:

const size_t SIZE = 30;
string line[SIZE]; // creates SIZE empty strings
size_t i=0;
while(!myfile.eof() && i < SIZE) {
  getline(myfile,line[i]); // read the next line into the next string
  ++i;
} 

for (i=0; i < SIZE; ++i) {
  if (!line[i].empty()) { // print only if there is something in the current line
    cout << i << ". " << line[i];
  }
}

你可以维护一个计数器来查看你存储了多少行(而不是检查空行) - 这样你也可以正确地打印空行:

const size_t SIZE = 30;
string line[SIZE]; // creates SIZE empty strings
size_t i=0;
while(!myfile.eof() && i < SIZE) {
  getline(myfile,line[i]); // read the next line into the next string
  ++i;
}
size_t numLines = i;

for (i=0; i < numLines; ++i) {
  cout << i << ". " << line[i]; // no need to test for empty lines any more
}

注意:您最多只能存储SIZE行。如果您需要更多,则必须在代码中增加SIZE。稍后您将了解std::vector<>,它允许您根据需要动态增大大小(因此您无需跟踪存储的数量)。

注意:使用SIZE之类的常量只允许您在一个地方更改大小

注意:您应该在eof()之上添加对输入流中的错误的检查:如果读取失败而不是到达文件的末尾:

while (myfile && ...) {
  // ...
}

此处myfile转换为布尔值,表示是否可以使用它(true)或不使用false


<强>更新

我刚刚意识到你的意思是:你想要将输入读作一系列单词(用空格分隔),但是将它们显示为行。在这种情况下,您将需要数组数组来存储每一行​​

string line[SIZE1][SIZE2];

其中SIZE1是您可以存储的最大行数,SIZE2是每行可以存储的最大字数

填写此矩阵会更复杂:您需要逐行读取输入,然后分隔行内的单词:

string tmp; // temporary string to store the line-as-string
getline(myfile, tmp);
stringstream ss(tmp); // convert the line to an input stream to be able to extract
                      // the words
size_t j=0; // the current word index
while (ss) {
  ss >> line[i][j]; // here i is as above: the current line index
  ++j;
}

输出:

for (i=0; i < numLines; ++i) {
  cout << i << ". ";
  for (size_t j=0; j < SIZE2; ++j) {
    if (!line[i][j].empty()) {
      cout << line[i][j] << " ";
    }
  }
}

答案 2 :(得分:1)

这个怎么样..。

vector <string> v;
string line;    
ifstream fin("love.txt");
while(getline(fin,line)){
    v.push_back(line);
}
相关问题