Reading in a text file into a string array while ignoring single characters

I am trying to read in a text file into a string array. I am using a for loop to do that. But i have no idea how to get rid of single character words, such as: "a" "-" "." "," (Ignoring special characters and single letters). I appreciate your time, thank you so much.




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
39
40
41
42
43
44
45
46
#include "pch.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
	//first ask the user for a location + name from where to read the file and location + name where to save the output file,
	string infile;
	string outfile;
	cout << "Enter the file location of file you want to read in:" << endl;
	cin >> infile;
	ifstream fin(infile);


	if (!fin.is_open()) {
		cout << "ERROR ON OPENING FILE" << endl;
		exit(1);
	}
	else {
		cout << "File successfully opened" << endl;
	}


	cout << "Enter the file location and name of the output file:" << endl;
	cin >> outfile;
	ofstream fout(outfile);



	//read the contents into an array, ignoring single character words,
	string wordArray[1024];
	if (fin.is_open()) {	
		for (int i = 0; i < 1024; ++i) {
			fin >> wordArray[i];
			cout << wordArray[i] << endl;
		}
	}


	cout << "Your array printed above" << endl;
	cout << "------------------------" << endl;

Last edited on
after reading an offending word, if string.length() == 1 then don't store/print/process it, just throw it away and skip to next word.
I was able to change my code to this:

1
2
3
4
5
6
7
8
9
10
string wordArray[1024];
	if (fin.is_open()) {	
		for (int i = 0; i < 1024; ++i) {
			fin >> wordArray[i];
			if (wordArray[i].length() == 1) {
				wordArray[i].erase();
			}
			cout << wordArray[i] << endl;
		}
	}


However, it is now outputting an empty line where the special character used to be.
Should i not be using the erase function? Thank you for the reply though @jonnin
Last edited on
1
2
3
4
5
constexpr int max_words = 1024;
std::string words[max_words]
std::string word; 
for (int i = 0; i < max_words && std::cin >> word; )
  if (word.size() > 1) words[i++] = std::move(word);
Last edited on
Topic archived. No new replies allowed.