-1

I am trying to read from file into an array. I know I need to read until I hit a space (' ') and then when I hit the end of the line ('\n') skip to the next line. I am not sure how to do this. I tried reading until (array != ' ') but this does not seem to work. Any tips?

Input:

SALESMAN MONTH PROGRAM WRITE

SEE THE BLUE SKY

CAT THROUGH A RAN

THE TOP TUMBLED TO

WHENEVER WATER WAS WHITE

CHARLES CHECK CHEERS CHEAP

A BLUE CLEAR SKY

PAIR PAUL PETER PHILLIP

ADELE CARY DAVID ELAINE

TABLE CHAIR BED DOG

notescrew
  • 3,072
  • 4
  • 21
  • 36
  • Hi, you mention that you have some code. Would you show it to us? – skratchi.at Nov 19 '19 at 07:09
  • Welcome to StackOverflow. Please read [How to ask](https://stackoverflow.com/help/how-to-ask) so people can help you more and you can get proper answers. – paxbun Nov 19 '19 at 07:10
  • `while (!ins.eof()) { str1 = 'a'; while (str1 != ' ') { ins >> str1; } }` – CoolMcDougal Nov 19 '19 at 07:18
  • [edit](https://stackoverflow.com/posts/58928381/edit) your code into your question rather than posting it as a comment – Alan Birtles Nov 19 '19 at 08:05
  • Change your perspective: first read an entire line, then divide that line. Read about `std::istringstream` and `std::getline` in your favourite C++ book. – molbdnilo Nov 19 '19 at 08:46

2 Answers2

1

Here's the proper C++ way of reading the file. This code reads the desired file line by line and stores the words into a vector. You can use this as a reference in your own application.

#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>

int main (int argc, char *argv[])
{
    std::vector<std::string> words;

    std::ifstream inFile;

    inFile.open("text.txt");
    if (!inFile) {
        std::cerr << "Failed to open file" << std::endl;
        return -1;
    }

    std::string input;

    /* read file line by line */
    while(std::getline(inFile, input)) {
        std::stringstream ss{input};
        std::string word;

        /* read words separated by space*/
        while (ss >> word) {
            words.push_back(word);
        }
    }

    std::cout << "Printing words in file" << std::endl;

    for(auto &word : words) {
        std::cout << word << std::endl;
    }

    return 0;
}
Yasir Khan
  • 585
  • 3
  • 9
-3

maybe you need just

   std::ifstream file(filename);
   char ch;
   while (!file.eof())
   {
      file >> ch;
      if (ch == ' ')
      {
          // do something
      }
   }
halong
  • 68
  • 4
  • 4
    Required reading: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – user4581301 Nov 19 '19 at 07:24