Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将文件转换为字符串数组C++;_C++ - Fatal编程技术网

C++ 将文件转换为字符串数组C++;

C++ 将文件转换为字符串数组C++;,c++,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;

我需要读取一个文件并将其转换为字符串数组,但当它读取该文件时,它不会在数组中放入任何内容。 以下是我当前的代码:

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 it\n";
    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;
}
字符串代码[200];
字符串名;
内线;
字符串文件名;
int readfile(){
河流充填;
int计数器=0;
cout>文件名;
countlines();//计算文件的总行数
inFile.open(文件名);
if(infle.fail())
{
姓名;
对于(int i=0;i>代码[i];
如果(!infle)

cout这是一个更简单的行读取实现,如果文件的行数超过200行,则不会崩溃:

vector<string> code;
string s;
while (getline(inFile, s)) {
    code.push_back(s);
}
矢量码;
字符串s;
while(getline(infle,s)){
代码。推回(s);
}

这是一个更简单的行读取实现,如果文件的行数超过200行,则不会崩溃:

vector<string> code;
string s;
while (getline(inFile, s)) {
    code.push_back(s);
}
矢量码;
字符串s;
while(getline(infle,s)){
代码。推回(s);
}
#包括
#包括
#包括
#包括
使用名称空间std;
矢量线;
bool readFile(字符串文件名){
ifstream文件;
弦线;
打开(filename.c_str());
如果(!file.is_open()){
返回false;
}
while(getline(文件,行)){
线。推回(线);
}
返回true;
}
int main(){
readFile(“test.txt”);
对于(int i=0;i
inFile.open(filename);
致:

你需要改变

inFile.open(filename);
致:


“不工作”是一个非常模糊的描述。您输入的文件名是什么?“不工作”是一个非常模糊的描述。您输入的文件名是什么?如何在for循环中使用行?for(int I=0;Iifstream
of stream
允许您为文件名传入
std::string
。现代实现支持此功能。考虑到他没有提到编译器错误,他的编译器肯定也支持此功能。@BenjaminLindley是真的。他没有提到这一点。我只是提供了这一点,因为我的g++编译器不会使用std::string作为参数值编译代码。可能不会。在C++11中,
ifstream
of stream
允许您为文件名传入
std::string
。现代实现支持此功能。考虑到没有提到编译器错误,他的编译器肯定也支持它。@BenjaminLindley True。他没有提到这一点。我只是提供了这一点,因为我的g++编译器不会用std::string作为参数值编译代码。