-1

I've been trying to write some text in a file then store this text in a char array, but it keeps ignoring spaces. this is the code I've been trying. thanks!

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++;
      }
  • 3
    First of all please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Some programmer dude Mar 12 '19 at 16:45
  • Then for your problem: The "input" operator `>>` skips spaces. You might be interested to learn about the [`std::noskipws`](https://en.cppreference.com/w/cpp/io/manip/skipws) manipulator. – Some programmer dude Mar 12 '19 at 16:46
  • 1
    Lastly, you really need to add both some error checking in your code, as well as bounds checking. What happens if the you fail top open any of the files? Of if the input file is longer than 100 characters? And more importantly, where do you add the null-terminator `'\0'` to your array? Oh, and for the last loop, why not use a `for` loop? And if you null-terminate the array, why not output it as a string instead of character by character? – Some programmer dude Mar 12 '19 at 16:48
  • @Someprogrammerdude thanks a lot I'll keep that in mind. – Amna Alnajjar Mar 12 '19 at 16:49

1 Answers1

0

I think you must read this Read ASCII into std::string

Add this code to yours

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;

The output of all

AmnaAlhadiAlnajjar
new: Amna Alhadi Alnajjar
new: Amna Alhadi Alnajjar
LeoLopez
  • 181
  • 1
  • 3