RnD
RnD

Reputation: 1069

input text from a file to a char variable

I have a variable

ifstream inFile("stuff.txt");

in the stuff.txt file there's a full sentance:

The quick brown fox jumps over the lazy dog

How do I put it into a char array with all the spaces?

char text[250];
inFile >> text;

gets me to the first space, nothing else.

Upvotes: 0

Views: 189

Answers (2)

hmjd
hmjd

Reputation: 121961

Use ifstream::getline() to read into a char array or use std::getline() to read into a std::string. When you use inFile >> text whitespace will act as a delimiter, which is why it stops at the first space.

Using std::getline() to read into a std::string removes the requirement for specifying the maximum number of characters to read. This removes the potential for buffer overruns and avoids the added complexity of coping with partially read lines (if a line was > 250 in this case for example).

Always check the result of IO operations immediately:

 std::ifstream inFile("stuff.txt");
 if (inFile.is_open())
 {
     std::string line;
     if (std::getline(inFile, line))
     {
         // Use 'line'.
     }
 }

Upvotes: 3

Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

while (!inFile.eof()) {

    inFile >> text;

 }

Upvotes: 0

Related Questions