Roland
Roland

Reputation: 965

C++ putting text from a file to a char

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++;
}

Upvotes: 0

Views: 120

Answers (2)

Mohammad Tayyab
Mohammad Tayyab

Reputation: 696

'>>' 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++;
    }

Upvotes: 2

Adir Ratzon
Adir Ratzon

Reputation: 181

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

Upvotes: 0

Related Questions