0

So I have multiple words in a text file and I want to put all of them in a char. The problem is that it doesn't keep the space between the words too. My code:

ifstream f("file.txt");
char a[100];
int i=0;
while(f){
f>>a[i];
i++;
}
Roland
  • 487
  • 1
  • 7
  • 11
  • Can you show us how your file.txt structure is? – Starlord Mar 24 '17 at 21:56
  • And how are you checking the contents of the array? – rcs Mar 24 '17 at 21:58
  • well it just has text in it. Let's say for exemple that I have in a file "832 John something" I want to put those words exactly how they are with the spaces between in a char. I'm checking it with a for loop. first with a n=strlen(a), to check the length of it – Roland Mar 24 '17 at 22:00

2 Answers2

2

'>>' stream operator do not detect space in file. you we have cin.get(charVariable); function for it. in your case it will be f.in(a[i]);

This will solve your problem;

ifstream f("File.txt");
    char a[100];
    int i = 0;
    while (f){
        f.get(a[i]); //use it instead of f>>a[i];
        i++;
    }
Mohammad Tayyab
  • 666
  • 4
  • 21
0

This happens because your'e reading the file word by word. You should use the std::string contents function to read the whole text char by char (space char included).

Please read Nemanja Boric answer at This Page

Community
  • 1
  • 1
Adir Ratzon
  • 152
  • 6