我正在为学校做一个项目,我需要从文件中读取文本。
听起来很简单,除了我的教授对项目施加了限制:NO STRINGS (“不允许使用字符串数据类型或字符串库。”)
我一直在使用 char 数组解决这个问题;但是,我不确定如何使用 char 数组从文件中读入。
这是来自另一个网站的示例,关于如何读取带有字符串的文件。
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
这里重要的一行是 while ( getline (myfile,line) );
getline
接受一个 ifstream 和一个 string(不是字符数组)。
感谢任何帮助!
最佳答案
使用cin.getline
。有关格式,请参阅此站点:cin.getline .
你可以这样写:
ifstream x("example.txt");
char arr[105];
while (x.getline(arr,100,'\n')){
cout << arr << '\n';
}
关于c++ - 如何使用 C 字符串读取 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381199/