Answer to Question #75741 in C++ for Alex

Question #75741
Read a set of strings (one at a time) from a text file, input.txt. Each string begins on a new line in the input file and the number of strings is unknown. A line containing five & signs indicates the end of input data. The only additional characters, besides letters, permitted in a string, are spaces and punctuation characters (e.g. -, ’, “, .). A string may contain both uppercase and lowercase letters. Assume all input data are valid.
1
Expert's answer
2018-04-12T07:41:17-0400
#include <iostream>
#include <string>
#include <list>
#include <iterator>
#include <fstream>

using namespace std;

int main()
{
// array of string
list<string> str;

// read string from file "input.txt"
ifstream file;
string s;
file.open("input.txt", ios_base::in);
if (file.is_open()) {
while (getline(file, s)) {
int count = 0;
// test string for containing five & signs
for (int i = 0; i < s.length(); i++) {
if (s[i] == '&') count++;
}
if (count == 5) break;
// add string to array
str.push_back(s);
}
} else { cout << "File <input.txt> not found" << endl; };
file.close();

// display set of strings
int n = 0;
cout << "Set of strings:" << endl;
for (string a : str) {
n++;
cout << n << ": " << a << endl;
}

// waiting for press ane key
cout << endl;
cout << "Press any key...";
cin.get();
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS