C++ 如何从文件中读取文本行并将它们放入数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11546177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read lines of text from file and put them into an array
提问by newbieprogrammer
I created a text file love.txt
:
我创建了一个文本文件love.txt
:
i love you
you love me
How do I store them into separate array, namely line1
and line2
and then display them out in console?
如何将它们存储在独立的阵列,即line1
和line2
,然后在控制台显示出来?
#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";
}
}
回答by Mahesh Meniya
Try specifying the last argument as '\n' in both getline()
functions:
尝试在两个函数中将最后一个参数指定为'\n'getline()
:
getline(myfile, line1[a], '\n');
instead of
代替
getline(myfile, line1[a], ' ');
回答by Attila
You can think of a string as an array of characters, so you will only need one array of strings:
您可以将字符串视为字符数组,因此您只需要一个字符串数组:
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];
}
}
You could maintain a counter to see how many lines you have stored into (instead of checking for empty lines) as well -- this way you will properly print empty lines as well:
您也可以维护一个计数器来查看您存储了多少行(而不是检查空行)——这样您也可以正确打印空行:
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
}
Note: you will be able to store only up to SIZE
lines. If you need more, you will have to increase SIZE
in the code. Later on you will learn about std::vector<>
that allows you to dynamically grow the size as needed (so you won't need to keep track of how many you stored).
注意:您最多只能存储SIZE
行。如果需要更多,则必须增加SIZE
代码。稍后您将了解std::vector<>
它允许您根据需要动态增加大小(因此您无需跟踪存储的数量)。
Note: the use of constants like SIZE
allows you to change the size in one place only
注意:使用常量 likeSIZE
允许您仅在一处更改大小
Note: you should add a check for errors in the input stream on top of eof()
: in case there was a read failure other than reaching the end of the file:
注意:您应该在输入流中添加对错误的检查eof()
: 以防读取失败而不是到达文件末尾:
while (myfile && ...) {
// ...
}
here myfile
is converted to a boolean value indicating if it is OK to use it (true
) or not (false
)
heremyfile
转换为布尔值,指示是否可以使用 ( true
) 或不使用 ( false
)
Update:
更新:
I just realized what you are after: you want to read the input as series of words (separated by space), but display them as lines. In this case, you will need arrays-of-arrays to store each line
我刚刚意识到您在追求什么:您想将输入读取为一系列单词(以空格分隔),但将它们显示为行。在这种情况下,您将需要数组数组来存储每一行
string line[SIZE1][SIZE2];
where SIZE1
is the maximum amount of lines you can store and SIZE2
is the maximum amount of words you can store per line
其中SIZE1
是您可以存储SIZE2
的最大行数,是每行可以存储的最大单词数
Filling this matrix will be more complex: you will need to read the input line-by-line then separate the words within the line:
填充这个矩阵会更复杂:您需要逐行读取输入,然后将行内的单词分开:
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;
}
Output:
输出:
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] << " ";
}
}
}
回答by edrianhadinata
How about this.. .
这个怎么样.. 。
vector <string> v;
string line;
ifstream fin("love.txt");
while(getline(fin,line)){
v.push_back(line);
}