将文件转换为字符串数组C++
Convert files into string array C++
我需要读取一个文件并将其转换为字符串数组,但是当它读取文件时,它不会在数组中放置任何内容。这是我当前的代码:
string code[200];
string name;
int lines;
string filename;
int readfile(){
ifstream inFile;
int counter = 0;
cout << "Which file would you like to open?n";
cin >> filename;
countlines();//counts total lines of file
inFile.open(filename);
if(inFile.fail())
{
cout << "File did not open correctly, please check itn";
system("pause");
exit(0);
//return 1;
}
inFile >> name;
for (int i=0;i < lines; i++)
{
inFile >> code[i];
if (!inFile)
cout << "Error" << endl;
break;
}
inFile.close();
cout << "Now opened: " << name << endl;
return 0;
}
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
vector<string> lines;
bool readFile(string filename){
ifstream file;
string line;
file.open(filename.c_str());
if(!file.is_open()){
return false;
}
while (getline(file, line)) {
lines.push_back(line);
}
return true;
}
int main(){
readFile("test.txt");
for(int i = 0; i < lines.size(); ++i){
cout << lines[i] << endl;
}
return 0;
}
这是一个更简单的行读取实现,如果文件超过 200 行,它不会崩溃:
vector<string> code;
string s;
while (getline(inFile, s)) {
code.push_back(s);
}
你需要改变
inFile.open(filename);
自:
inFile.open(filename.c_str());
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '