【问题标题】:how to store a text file into a char array with spaces?如何将文本文件存储到带有空格的字符数组中?
【发布时间】:2019-03-12 16:44:12
【问题描述】:

我一直在尝试在文件中写入一些文本,然后将这些文本存储在 char 数组中,但它一直忽略空格。 这是我一直在尝试的代码。 谢谢!

ofstream ofile;
    ofile.open("file.txt");
    int i,item;
    char array[100];
    ofile << "Amna Alhadi Alnajjar" << endl;
     ofile.close();
     ifstream ifile;
     ifile.open("file.txt");
       i=0;
      while(!ifile.eof())
      {
          ifile >> array[i];
          i++;
      }
      ifile.close();
      i=0;
      while(array[i]!='\0')
      {
         cout<< array[i];
          i++;
      }

【问题讨论】:

  • 那么对于您的问题:“输入”运算符&gt;&gt; 跳过空格。您可能有兴趣了解std::noskipws 操纵器。
  • 最后,您确实需要在代码中添加一些错误检查以及边界检查。如果您无法打开任何文件,会发生什么?如果输入文件超过 100 个字符?更重要的是,您在哪里将空终止符 '\0' 添加到您的数组中?哦,对于最后一个循环,为什么不使用for 循环呢?如果你对数组进行空终止,为什么不将它作为一个字符串而不是一个字符一个字符地输出呢?
  • @Someprogrammerdude 非常感谢,我会记住这一点。

标签: c++ arrays file


【解决方案1】:

我认为您必须阅读此Read ASCII into std::string

将此代码添加到您的代码中

std::string str;
ifstream ifile2("file.txt");

ifile2.seekg(0, std::ios::end);   
str.reserve(ifile2.tellg());
ifile2.seekg(0, std::ios::beg);

str.assign((std::istreambuf_iterator<char>
           (ifile2)),std::istreambuf_iterator<char>());

const char * cad = str.c_str();
cout << endl;
cout << "new: " << str;
cout << "new: " << cad;

所有的输出

AmnaAlhadiAlnajjar
new: Amna Alhadi Alnajjar
new: Amna Alhadi Alnajjar

【讨论】:

    猜你喜欢
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 2020-01-21
    • 1970-01-01
    相关资源
    最近更新 更多