c ++:逐行读取文件 [英] c++: Reading a file line by line
问题描述
我遇到了下面的代码来完成这个任务:
我想知道是否有一个C ++方法打开一个文件, / p> #include< iostream>
#include< fstream>
using namespace std;
int main(){
ifstream myfile;
myfile.open(example.txt);
return 0;
}
我鼓励不要使用任何C函数或命令。
事情是,我的example.txt是一个字符串形式,使用str.c_str()是一个C函数,所以我想我有两种方法解决问题。
有没有另一种方式从文件逐行读取输入?也许使用将接受一个字符串作为文件路径的参数的东西?有没有C ++的做事方式? :)
或者,是否有另一种方法将字符串转换为const char *,这是myfile.open()函数需要什么?
非常感谢!
编辑:我缺乏实用性和研究,所以我认为c_str ,而不是。我很抱歉。因为它没有找到我的答案。
C ++ 11的 fstream
构造函数接受 string
。在大多数情况下,您想使用 fstream
的构造函数,而不是 .open()
- 您保存一行和一个函数调用。
要逐行读取文件,您应该使用 std :: getline()
。
string :: c_str()
仍然是C ++函数,而不是C一个,以及 fstream
的构造函数 const char *
。大多数(如果不是全部,我不是100%肯定)C标准库函数也包括在C ++标准中。
I'm wondering if there's a C++ way of opening a file and reading the input line by line.
I encountered the following code that accomplishes the task:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myfile;
myfile.open ("example.txt");
return 0;
}
I'm encouraged to not use any C functions or commands.
The thing is, my "example.txt" is in the form of a string, and using str.c_str() is a C function, so I guess I have two ways to solve the issue.
Is there another way to read input from a file line by line? Perhaps using something that will accept a string as a parameter for the filepath? Is there a C++ way of doing things? :)
Or, is there another way to convert the string in to a const char *, which is what the myfile.open() function needs?
Many thanks in advance!
EDIT: My lack of practivity and research led me to think c_str() was a C function, and it isn't. My apologies. Since it isn't I have found my answer.
C++11's fstream
constructor accepts string
. In most cases, you want to use fstream
's constructor, rather than .open()
- you save one line and one function call.
For reading the file line-by-line, you should use std::getline()
.
Also note that string::c_str()
is still C++ function, not C one, as well as fstream
's constructor taking const char *
. Most of (if not all, I'm not 100% sure) C standard library function are also included in C++ standard.
这篇关于c ++:逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!