C++ insertion sort from a txt file - c++

I have to read from a .txt file and out it with a different .txt file. I have to use insertion sort in order to sort them based on two numbers. I could only get this far, I don't know how to do insertion sort in this program where I have two numbers to sort to.
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
int serialno[100], suratno[100], ayatno[100];
string order;
string str;
char ch;
int i = 0;
int j, temp;
ifstream fin;
fin.open("text.txt");
if(!fin)
{
cout << "Cannot open file \'text.txt\'! Quitting.\n";
exit(0);
}
while(fin)
{
fin.get(ch); //gets .
getline(fin, order, '('); //allegedly it removes the delimiter char from stream too
fin >> suratno;
fin.get(ch); //gets :
fin >> ayatno;
fin.get(ch); //gets )
fin.get(ch); //gets \n
cout << serialno << "." << order << "("<<suratno<<":<<ayatno<<")\n";
}
fin.close();
//sort algorithm
for (int i = 0; i < length; i++){
j = i;
while (j > 0 && suratno [j] < suratno [j-1]){
temp = suratno [j];
suratno [j] = suratno [j-1];
suratno [j-1] = temp;
j--;
cout << serialno << endl;
}
}
}
ofstream fout;
fout.open("newtext.txt");
if(!fout)
{
cout << "Cannot open output file\'orderedquranorders.txt\'!Quitting.\n";
exit(0);
}
i = 0;
//write sorted list to output file
fout.close();
cout << i << " orders successfully sorted and written.\n";
}
this is the text file (numbers in bracket should be used, firstly with number before colon, and secondly with number after colon):
1. Do not be rude in speech (3:159)
2. Restrain Anger (3:134)
3. Be good to others (4:36)
4. Do not be arrogant (7:13)
5. Forgive others for their mistakes (7:199)
6. Speak to people mildly (20:44)
7. Lower your voice (31:19)
8. Do not ridicule others (49:11)
9. Be dutiful to parents(17:23)
current output:
Do not be rude in speech (3:159)
Restrain Anger (3:134)
Be good to others (4:36)
Be dutiful to parents(17:23)
expected output:
Restrain Anger (3:134)
Do not be rude in speech (3:159)
Be good to others (4:36)
Be dutiful to parents(17:23)
sorted in terms of both the numbers and the serial no stays the same

In order to compare two pair of numbers, you can make comparisons like:
if(suratno[i] < suratno[i-1] || (suratno[i] == suratno[i-1] && ayatno[i] < ayatno[i-1])){
/* swap */
}
Or you can use one expression: expr = suratno * 10000 + ayatno. And make just one comparison:
if(expr[i] < expr[i-1]){
/* swap */
}
Also, I have a few observations about your algorithm/code:
Don't use using namespace std. Specially in big programs, because it can cause obscure bugs (see an example here). Instead use using std::<name> when you want to avoid std::. Ex. using std::string. In general, avoid using namespace xxxx.
I see you did parse the input lines manually, I prefer to use regular expressions, that are much more versatile and powerful, but requires a little learning.
When it's necessary to write an error message, always write to stderr stream cerr in C++.
In the sort algorithm, it's better start in 1 than 0, because the first item doesn't have a previous item to compare with.
Finally the swap can be done with an existent C++ function.
Here is your code reorganized and using regular expressions that I tried to explain as much as possible:
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <vector>
#include <algorithm>
using std::string;
struct Line {
int expr; // Expression used to compare
string text; // Original line without initial number
};
int main() {
std::regex linePattern(
"\\d+" // 1 or more digits
"\\. " // '. ' (dot followed by 1 space)
"(" // begin char group #1
".*" // zero or more chars
"\\(" // '(' (left parenthesis)
"(\\d+)" // char group #2 (suratno: 1+ digits)
":" // ':' (colon)
"(\\d+)" // char group #3 (ayatno: 1+ digits)
"\\)" // ')' (right parenthesis)
")" // end char group #1
);
std::smatch groups; // Regular expression found char groups
std::vector<Line> lines; // Vector to store the readed lines
// Read lines parsing content
std::ifstream fin("text.txt");
if(!fin){
std::cerr << "Cannot open file 'text.txt'! Quitting.\n";
return 1;
}
string line;
while (std::getline(fin, line))
if (std::regex_search(line, groups, linePattern) && groups.size() > 0) {
int suratno = std::stoi(groups[2]);
int ayatno = std::stoi(groups[3]);
int compExpr = suratno * 10000 + ayatno; // assumes ayatno < 10,000
lines.push_back({ compExpr, groups[1] });
}
fin.close();
// sort algorithm (better start in 1)
for (size_t i = 1; i < lines.size(); i++)
for (size_t j = i; j > 0 && lines[j].expr < lines[j - 1].expr; j--)
std::swap(lines[j], lines[j - 1]);
std::ofstream fout("newtext.txt");
if(!fout){
std::cerr << "Cannot open output file 'orderedquranorders.txt'! Quitting.\n";
return 1;
}
for (size_t i = 0; i < lines.size(); i++)
fout << i + 1 << ". " << lines[i].text << std::endl;
fout.close();
std::cout << lines.size() << " orders successfully sorted and written.\n";
return 0;
}
Note: The regular expression is really one string "\\d+\\. (.*\\((\\d+):(\\d+)\\))", I used a C/C++ feature that concatenates strings separated by spaces before compilation, so the compiler sees only one string.
Don't forget to compile with -std=c++11 option.

using namespace std; is considered bad practice and can be dangerous sometimes. Check this
Here is your solution:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
int suratno[100], ayatno[100];
std::string order[100];
char ch;
int count = 0;
int tempInt;
std::string tempStr;
std::ifstream fin;
fin.open("text.txt");
if (!fin)
{
std::cout << "Cannot open file \'text.txt\'! Quitting.\n";
exit(0);
}
else
{
while (fin)
{
fin.get(ch); //gets the numbers
fin.get(ch); //gets .
getline(fin, order[count], '('); //allegedly it removes the delimiter char from stream too
fin >> suratno[count];
fin.get(ch); //gets :
fin >> ayatno[count];
fin.get(ch); //gets )
fin.get(ch); //gets \n
std::cout << count + 1 << "." << order[count] << "(" << suratno[count] << ":" << ayatno[count] << ")\n";
count++;
}
}
fin.close();
std::cout << std::endl;
// sort algorithm (we must sort two times)
for (int i = 0; i < count; i++)
{
for (int j = i; j > 0 && suratno[j] < suratno[j - 1]; j--)
{
tempInt = suratno[j];
suratno[j] = suratno[j - 1];
suratno[j - 1] = tempInt;
tempInt = ayatno[j];
ayatno[j] = ayatno[j - 1];
ayatno[j - 1] = tempInt;
tempStr = order[j];
order[j] = order[j - 1];
order[j - 1] = tempStr;
}
}
for (int i = 0; i < count; i++)
{
for (int j = i; j > 0 && suratno[j] == suratno[j - 1] && ayatno[j] < ayatno[j - 1]; j--)
{
tempInt = ayatno[j];
ayatno[j] = ayatno[j - 1];
ayatno[j - 1] = tempInt;
tempInt = suratno[j];
suratno[j] = suratno[j - 1];
suratno[j - 1] = tempInt;
tempStr = order[j];
order[j] = order[j - 1];
order[j - 1] = tempStr;
}
}
// print the sorted list just to check
for (int i = 0; i < count; i++)
{
std::cout << i + 1 << "." << order[i] << "(" << suratno[i] << ":" << ayatno[i] << ")\n";
}
// write sorted list to output file
std::ofstream fout;
fout.open("newtext.txt");
if (!fout)
{
std::cout << "Cannot open output file\'orderedquranorders.txt\'!Quitting.\n";
exit(0);
}
else
{
for (int i = 0; i < count; i++)
{
fout << i + 1 << "." << order[i] << "(" << suratno[i] << ":" << ayatno[i] << ")\n";
}
}
fout.close();
std::cout << std::endl;
std::cout << count << " orders successfully sorted and written.\n";
return 0;
}

Related

what can I get sum that string tokens converted int in C++?

I need to sum 100, 200, 300 in a.txt
a.txt
2323|A|5|0|2|100
2424|B|6|1|3|200
2525|C|7|2|4|300
so I opened this file, and read line by line using getline(), and tokenized.
main.cpp
for (std::string each; std::getline(split, each, split_char); tokens.push_back(each)) {
for (int i = 0; i < tokens.size(); i++) {
std::cout << tokens[i] << std::endl;
tokens.pop_back();
}
}
As expected, that code printed singly of all things.
so I thought using token index to sum values. but my code have error.
"vector subscript out of range" or no compile.
first try
for (std::string each; std::getline(split, each, split_char); tokens.push_back(each)) {
for (int i = 0; i < tokens.size(); i++) {
std::cout << tokens[i] << std::endl;
tokens.pop_back();
std::cout << tokens[5] << std::endl;
std::cout << tokens[11] << std::endl;
std::cout << tokens[17] << std::endl;
int a = 0;
int b = 0;
int c = 0;
int sum = 0;
a = stoi(tokens[5]);
b = stoi(tokens[11]);
c = stoi(tokens[17]);
sum = (a + b + c);
std::cout << sum << std::endl;
}
}
second try
for (std::string each; std::getline(split, each, split_char); tokens.push_back(each)) {
if(tokens.size() > 4) {
for (int k = 0; k < ((tokens.size() - 5) / 6) + 1; k++) {
int sum = 0;
int change = 0;
int j = 0;
j = 6 * k + 5;
change = stoi(tokens[j]);
sum += change;
std::cout << sum << std::endl;
tokens.pop_back();
}
}
}
what should I do sum value? and I'm wondering that tokens.size()`s meaning except meaning "size" because second for statement always get an error if not exactly correcting i < tokens.size()
You are modifying the tokens vector while you are looping through it. Don't do that. You are affecting its size(), which accounts for why you are able to go out of bounds.
You say that you need to sum only the last token of each line. But that is not what your code is trying to do. There is no need for an inner for loop at all. Simply split each line into a local tokens vector and then use tokens.back() to get the last token, eg:
std::string line;
int sum = 0;
while (std::getline(inFile, line))
{
std::istringstream iss(line);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, '|')) {
tokens.push_back(token);
}
// use tokens as needed...
token = tokens.back();
sum += std::stoi(token);
}
std::cout << sum << std::endl;
Live Demo
I would like to structure my code slightly differently.
Rather than try and do everything in the main function split your code up so that you read each line and validate it is correct:
#include <iostream>
#include <string>
// A structure representing the data we want to parse.
struct DataLine
{
int v1;
char c;
int v2;
int v3;
int v4;
int v5;
// An input operator that will read one line of data.
// If the data is valid will update the variable we are reading into.
friend std::istream& operator>>(std::istream& str, DataLine& data)
{
DataLine tmp;
char s[5];
std::string extra;
if ( str >> tmp.v1 >> s[0] && s[0] == '|'
&& str >> tmp.c >> s[1] && s[1] == '|'
&& str >> tmp.v2 >> s[2] && s[2] == '|'
&& str >> tmp.v3 >> s[3] && s[3] == '|'
&& str >> tmp.v4 >> s[4] && s[4] == '|'
&& str >> tmp.v5
&& std::getline(str, extra) && extra.empty())
{
// all the data was read and the line was valid.
// update the correct variable.
swap(tmp, data);
}
else {
// there was an issue.
// set the stream to bad so that reading will stop.
str.setstate(std::ios::badbit);
}
return str;
}
// Standard swap method.
friend void swap(DataLine& lhs, DataLine& rhs) noexcept
{
using std::swap;
swap(lhs.v1, rhs.v1);
swap(lhs.c , rhs.c );
swap(lhs.v2, rhs.v2);
swap(lhs.v3, rhs.v3);
swap(lhs.v4, rhs.v4);
swap(lhs.v5, rhs.v5);
}
};
Then the loop you use to read the data becomes really trivial to implement.
int main()
{
DataLine data;
int sum = 0;
// Now we can read the data in a simple loop.
while(std::cin >> data) {
sum += data.v5;
}
std::cout << "Sum: " << sum << "\n";
}

Finding the middle word in a string

As the title suggests, I'm having trouble trying to grab the middle word out of a string, I believe my formula is wrong but I'm not completely sure where to from here to fix the issue, any help is always appreciated thank you!
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string sentence="";
string middle="";
string midtemp="";
int count=0;
int mid=0;
cout << "Enter a sentence:" << endl;
getline(cin,sentence); //gets user input
for(int count =0; count<sentence.length();count++){
letter=sentence.substr(count,1);
int mid = sentence.length();
if (midtemp.length()>middle.length())
{ midtemp=middle;}
if (sentence[count]!=' ')
{ if(mid%2==0);
reverse(longest.rbegin(),longest.rend()); //shows the word not backwards
cout<<"Middle word is: " << sentence.substr(mid/2 -1) <<"\n" << endl;
break; //presents info to user
}
else(mid%2!=0);
{ mid/2;
cout<<"Middle word is: " << sentence.substr(mid/2 -1) <<"\n" << endl;
break; //presents info to user if number is even
}
}
To find the middle word in a string with three words use:
size_t begin_index = sentence.find(' ') + 1;
size_t end_index = sentence.find(' ', begin_index);
size_t length = end_index - begin_index;
string middle_word = sentence.substr(begin_index, length);
To find the middle word in a string with any odd number of words use:
// create string stream from sentence
istringstream ss(sentence);
// split string stream into vector of words
vector<string> words(istream_iterator<string>(ss), {});
// get middle index
size_t middle_index = (words.size() - 1) / 2;
// get middle word
const auto& middle_word = words[middle_index];
If there are an even number of words, the result is either rounded up or down until C++11, after C++11 it is rounded down. (To the word before the middle space).
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char **argv) {
string input;
getline(cin, input);
vector<string> tokens;
string token;
for (size_t i = 0; i < input.length(); i++) {
char c = input[i];
if (c == ' ' || !input[i + 1]) {
if (!input[i + 1])
token += c;
tokens.push_back(token);
token = "";
continue;
}
token += c;
}
auto mid = tokens.size() % 2 == 0 ? tokens.begin() + tokens.size() / 2 - 1
: tokens.begin() + tokens.size() / 2;
cout << *mid;
return 0;
}

print 2nd word in a string with its size in C++

I am trying to make a program in which a user enters a string and i will print out the second word in the string with its size.
The delimiter's are space( ), comma(,) and tab( ).
I have used a character array and fgets to read from user and a character pointer that points to the first element of the array.
source code:
#include"iostream"
#include<stdio.h>
#include<string>
using namespace std;
// extract the 2nd word from a string and print it with its size(the number of characters in 2nd word)
int main()
{
char arr[30], arr1[30];
char *str = &arr1[0];
cout<<"Enter a string: ";
fgets(str, 30, stdin);
int i = 0, j, count = 1, p = 0; // count is used to find the second word
// j points to the next index where the first delimiter is found.
// p is used to store the second word found in character array 'arr'
while(*(str+i) != '\n')
{
if(*(str+i) == ' ' || *(str+i) == ',' || *(str+i) == ' ')
{
count++;
if(count == 2)
{
// stroing 2nd word in arr character array
j = i+1;
while(*(str+j) != ' ' || *(str+j) != ',' || *(str+j) != ' ')
{
arr[p] = *(str+j);
cout<<arr[p];
p++;
i++;
j++;
}
break;
}
}
i++;
}
arr[p+1] = '\0'; // insert NULL at end
i = 0;
while(arr[i] != '\0')
{
cout<<arr[i];
i++;
}
cout<<"("<<i<<")"<<endl;
return 0;
}
Help me out with this.
To start, don't use std::cin for testing. Just set a value in your code for consistency and ease of development. Use this page for a reference.
#include <iostream>
#include <string>
int main() {
std::string str("this and_that are the tests");
auto start = str.find_first_of(" ,\n", 0);
auto end = str.find_first_of(" ,\n", start + 1);
std::cout << str.substr(start, end - start);
return 0;
}
And this is still somewhat of a hack, it just depends where you are going. For instance the Boost library is rich with extended string manipulation. If you are going to parse out more than just one word it can still be done with string manipulations, but ad-hoc parsers can get out of hand. There are other tools like Boost Spirit to keep code under control.
The delimiters used when extracting from a stream depends on the locale currently in effect. One (cumbersome) way to change the extraction behaviour is to create a new locale with a special facet in which you specify your own delimiters. In the below example the new locale is used to imbue a std::stringstream instead of std::cin directly. The facet creation part is mostly copy/paste from other answers here on SO, so you'll find plenty of other examples.
#include <iostream>
#include <locale> // std::locale, std::ctype<char>
// https://en.cppreference.com/w/cpp/locale/ctype_char
#include <sstream> // std::stringstream
#include <algorithm> // std::copy_n
#include <vector> // a container to store stuff in
// facet to create our own delimiters
class my_facet : public std::ctype<char> {
mask my_table[table_size];
public:
my_facet(size_t refs = 0)
: std::ctype<char>(&my_table[0], false, refs)
{
// copy the "C" locales table to my_table
std::copy_n(classic_table(), table_size, my_table);
// and create our delimiter specification
my_table[' '] = (mask)space;
my_table['\t'] = (mask)space;
my_table[','] = (mask)space;
}
};
int main() {
std::stringstream ss;
// create a locale with our special facet
std::locale loc(std::locale(), new my_facet);
// imbue the new locale on the stringstream
ss.imbue(loc);
while(true) {
std::string line;
std::cout << "Enter sentence: ";
if(std::getline(std::cin, line)) {
ss.clear(); // clear the string stream from prior errors etc.
ss.str(line); // assign the line to the string stream
std::vector<std::string> words; // std::string container to store all words in
std::string word; // for extracting one word
while(ss>>word) { // extract one word at a time using the special facet
std::cout << " \"" << word << "\" is " << word.size() << " chars\n";
// put the word in our container
words.emplace_back(std::move(word));
}
if(words.size()>=2) {
std::cout << "The second word, \"" << words[1] << "\", is " << words[1].size() << " chars\n";
} else {
std::cout << "did not get 2 words or more...\n";
}
} else break;
}
}
#include"iostream"
#include<stdio.h>
#include<string>
#include <ctype.h>
using namespace std;
int main()
{
char c;
string str;
char emp = ' ';
cout<<"Enter a string: ";
getline (cin,str);
int j = 0, count = 1, counter = 0;
for (int i = 0; i < str.length() && count != 2; i++)
{
cout<< str[i] <<endl;
if( isspace(str[i]) || str[i] == ',' || str[i] == '\t' )
{
count++;
if(count == 2)
{
j = i+1;
while(j < str.length())
{
if (isspace(str[j]) || str[j] == ',' || str[j] == '\t')
{
break;
}
cout<<str[j];
counter++;
j++;
}
cout<<endl;
}
}
}
cout<<"size of the word: "<<counter<<endl;
return 0;
}
This is a simple answer to what you want, hope to help you.
// Paul Adrian P. Delos Santos - BS Electronics Engineering
// Exercise on Strings
#include <iostream>
#include <sstream>
using namespace std;
int main(){
// Opening Message
cout << "This program will display the second word and its length.\n\n";
// Ask for a string to the user.
string input;
cout << "Now, please enter a phrase or sentence: ";
getline(cin, input);
// Count the number of words to be used in making a string array.
int count = 0;
int i;
for (i=0; input[i] != '\0'; i++){
if (input[i] == ' ')
count++;
}
int finalCount = count + 1;
// Store each word in a string array.
string arr[finalCount];
int j = 0;
stringstream ssin(input);
while (ssin.good() && j < finalCount){
ssin >> arr[j];
j++;
}
// Display the second word and its length.
string secondWord = arr[1];
cout << "\nResult: " << arr[1] << " (" << secondWord.size() << ")";
return 0;
}

String subscript out of range error "C++"

This program takes a text file and changes each word into pig Latin. I have gotten everything to work but continue to get the error "subscript out of range". I have tried to change many things but cant get it to go away. Can someone explain why I am getting this error?
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
void piglatin ( string word[], string temp, ifstream & in, int num);
int main()
{
string word[300];
string original[300];
string temp;
ifstream in;
int i=0,
j=0,
x=0,
par=0,
length=0;
in.open("text.txt");
if (in.is_open()) { //Checks if file is open
cout << "\nFile is open....\n\n\n";
} else {
cout << "Error: Failed to open!\n";
cout << "Exiting program\n";
exit(-1);
}
cout<<"Original text\n\n";
do {//Continues while loop until no more input.
in >> original[x];
cout << original[x] << " ";
x++;
par = par + x;
} while (!in.eof());
cout<<"\n\n";
cout<<"Pig Latin\n\n";
piglatin(original,temp,in,par);
return 0;
}
void piglatin ( string word[], string temp, ifstream & in, int num)
{
int i=0, length, j=0,a=0;
for(j = 0; j < num; j++) {
string str (word[j]);
length = str.size();
temp[0] = word[j][0];
if ((temp[0] == 'a') ||
(temp[0] == 'e') ||
(temp[0] == 'i') ||
(temp[0] == 'o') ||
(temp[0] == 'u'))
{
word[j] += "way";
} else {
for(i = 0; i <= length-1; i++) {
word[j][i] = word[j][i+1];
}
word[j][length-1] = temp[0];
word[j] += "ay";
}
cout << word[j] << " ";
length = 0;
}
cout << "\n\n";
}
This statement
temp[0] = word[j][0];
is invalid because string temp is empty and you may not use the subscript operator with empty strings to store a character.
You could write before the for loop for example
temp.resize( 1 );
Also I do not see any sense in the parameter temp. Instead of string temp you could use in the function local variable char temp; because you are using temp only to store one character.
I believe you are missing a parameter to the ifstream: The ifstream object requires two parameters, a filename and a mode which describes the requested i/o mode for the file.
in.open("text.txt");
Should be:
in.open("text.txt", ifstream::in);
Here is a link to the API for ifstream.open:
http://www.cplusplus.com/reference/fstream/ifstream/open/

How to read lines of text from file and put them into an array

I created a text file love.txt:
i love you
you love me
How do I store them into separate array, namely line1 and line2 and then display them out in console?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line1[30];
string line2[30];
ifstream myfile("love.txt");
int a = 0;
int b = 0;
if(!myfile)
{
cout<<"Error opening output file"<<endl;
system("pause");
return -1;
}
while(!myfile.eof())
{
getline(myfile,line1[a],' ');
cout<<"1."<<line1[a]<<"\n";
getline(myfile,line2[b],' ');
cout<<"2."<<line2[b]<<"\n";
}
}
Try specifying the last argument as '\n' in both getline() functions:
getline(myfile, line1[a], '\n');
instead of
getline(myfile, line1[a], ' ');
How about this.. .
vector <string> v;
string line;
ifstream fin("love.txt");
while(getline(fin,line)){
v.push_back(line);
}
You can think of a string as an array of characters, so you will only need one array of strings:
const size_t SIZE = 30;
string line[SIZE]; // creates SIZE empty strings
size_t i=0;
while(!myfile.eof() && i < SIZE) {
getline(myfile,line[i]); // read the next line into the next string
++i;
}
for (i=0; i < SIZE; ++i) {
if (!line[i].empty()) { // print only if there is something in the current line
cout << i << ". " << line[i];
}
}
You could maintain a counter to see how many lines you have stored into (instead of checking for empty lines) as well -- this way you will properly print empty lines as well:
const size_t SIZE = 30;
string line[SIZE]; // creates SIZE empty strings
size_t i=0;
while(!myfile.eof() && i < SIZE) {
getline(myfile,line[i]); // read the next line into the next string
++i;
}
size_t numLines = i;
for (i=0; i < numLines; ++i) {
cout << i << ". " << line[i]; // no need to test for empty lines any more
}
Note: you will be able to store only up to SIZE lines. If you need more, you will have to increase SIZE in the code. Later on you will learn about std::vector<> that allows you to dynamically grow the size as needed (so you won't need to keep track of how many you stored).
Note: the use of constants like SIZE allows you to change the size in one place only
Note: you should add a check for errors in the input stream on top of eof(): in case there was a read failure other than reaching the end of the file:
while (myfile && ...) {
// ...
}
here myfile is converted to a boolean value indicating if it is OK to use it (true) or not (false)
Update:
I just realized what you are after: you want to read the input as series of words (separated by space), but display them as lines. In this case, you will need arrays-of-arrays to store each line
string line[SIZE1][SIZE2];
where SIZE1 is the maximum amount of lines you can store and SIZE2 is the maximum amount of words you can store per line
Filling this matrix will be more complex: you will need to read the input line-by-line then separate the words within the line:
string tmp; // temporary string to store the line-as-string
getline(myfile, tmp);
stringstream ss(tmp); // convert the line to an input stream to be able to extract
// the words
size_t j=0; // the current word index
while (ss) {
ss >> line[i][j]; // here i is as above: the current line index
++j;
}
Output:
for (i=0; i < numLines; ++i) {
cout << i << ". ";
for (size_t j=0; j < SIZE2; ++j) {
if (!line[i][j].empty()) {
cout << line[i][j] << " ";
}
}
}
My complete solution.
the config.txt file contains:
#URL WEB POP3 IMAP SMTP FTP DNS PING ORDER
st-xxxx.com 1 1 0 1 1 0 1 1
24.xxx.195.11 1 1 0 1 1 0 1 2
24.xxx.195.12 1 1 0 1 1 0 1 3
192.168.0.100 1 1 0 1 1 0 1 4
and my code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream myfile("config.txt");
if(!myfile)
{
cout<<"Error opening output file"<<endl;
system("pause");
return -1;
}
const size_t SIZE1 = 30;
const size_t SIZE2 = 10;
string line[SIZE1][SIZE2];
string tmp; // temporary string to store the line-as-string
size_t i=0; // the current line index
size_t j=0; // the current word index
while(!myfile.eof() && i < SIZE1) {
getline(myfile, tmp);
stringstream ss(tmp); // convert the line to an input stream to be able
//to extract the words
size_t j=0;
while (ss) {
ss >> line[i][j]; // here i is as above: the current line index
++j;
}
i++;
}
size_t numLines = i;
cout << numLines << "\n";
for (i=1; i <= numLines; ++i) {
for (size_t j=0; j < SIZE2; ++j) {
if (!line[i][j].empty()) {
cout << line[i][j] << " ";
}
}
cout << "\n";
}
cout << line[3][0] << "\n"; // print the third line first word
}
Hope tht helps anybody who is searching for this type of solution, even if the post is quite old.