c++ - 将文件内容复制到字符串

标签 c++ arrays fstream ifstream

我想将文本文件中的内容复制到string*char。如果我可以将文件内容复制到字符串的 array 中(每一行都是该 array 的一个元素),那就更好了。这是我的代码:

int main() {
   ifstream inFile;
   inFile.open("index.in.txt"); //index.in has in each line a name and at the end there is a "."
   char ab[11];
   int q=0;
   char *a[111];
   if (inFile.is_open()) {
      while (!inFile.eof()) {
         inFile >> ab; //i think i don't understand this line correctly
         a[q]=ab;
         cout<<a[q]<<endl;
         q++;
      }
   }
   else{ 
     cout<<"couldnt read file";
   }
   inFile.close();
   cout<<"\n"<<ab<<endl; //it shoud be "." and it is
   cout<<"\n"<<a[0]<<endl; //it should be "ion" but it gives me "."
   return 0;
}

array 中的所有值都等于最后一行是点

最佳答案

int main() {
   ifstream inFile;
   inFile.open("index.in.txt"); //index.in has in each line a name and at the end there is a "."
   std::vector< std::string > lines;
   std::string line;
   if (inFile.is_open()) {
      while ( getline( inFile, line ) ) {
         lines.push_back( line );
      }
   }
...

现在 lines 是一个字符串 vector ,每个都是来自文件的一行

关于c++ - 将文件内容复制到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291995/

相关文章:

c++ - 内置类型的对象是否具有特殊的静态初始化顺序优先级?

C++ 多态性和 vector ,将 vector 的派生类指向 vector 的基类

arrays - swift中连续数组的数据结构

javascript - 如何使用这样的代码使 div 淡出而不是消失? (JavaScript)

c++ - fstream 的奇怪问题。不能存储成员变量具有特定值的对象

c++ - 如何设置log10(0)的返回值?

c++ - 在与 Odeint 结合的类中使用特征矩阵引用

arrays - 在 bash 中创建一个包含数字序列的数组

c++ - 我无法使用 fstream 读取 .dat 文件

c++ - 如何从特定位置开始读取文件 C++