While loop

How would I go about running my while loop until the end of a string?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <cctype>
#include <sstream>


void outputString(std::ifstream&, std::string);
void translateString(std::string);

int main()
{
    std::ifstream inputFile;
    std::string translateText;
    std::string plString;
    inputFile.open("ASSGN8-A.txt");
   for(int i = 0; i < 10; i++)
   {
    std::getline(inputFile, translateText);
    std::cout << "English: " << translateText << std::endl;
    while(!translateText.empty())
    {

       plString = translateText.substr(0, translateText.find(" "));
       translateText.erase(0, translateText.find(" ") + 1);
       std::cout << plString << " ";
    }
    std::cout << std::endl;


   }



    return 0;
}
- for loop int i = 0 etc but subsequent code doesn't mention index i, meaning the program will read just the first line from the text; you need to have a i++ at the end of each loop if you want to read just 10 lines from the file. If you want to read the whole file there is no need for this counter, instead use if(inputFile) or while(inputFile) as required after opening it;
- it appears you are trying to read individual words (identified by the whitespace delimiter) from a given string but note that the interim string, p1string, that you are using to store each word needs to be saved somewhere before you move on to the next word. Otherwise the program will overwrite p1string with the latest word and ultimately it will print out the last word of each line

- so here's a simple program to save a read a string with getline(), split it into individual words and save these words somewhere and print them out to test ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
    const string& s("The rain in Spain falls mostly in the plain");
    const char token = ' ';
    istringstream stream(s);
    vector<string> v;
    for
    (string words; getline(stream, words, token); v.emplace_back(words) );

    for (auto& elem : v)
    {
        cout<<elem<<"\t";
    }
}

Topic archived. No new replies allowed.