Line counting algorithm not working..?

Hewlett-packard / Pavilion touchsmart amd a...
March 15, 2014 at 11:19:25
Specs: Windows 7, 8GB
I wrote this code which if you input something it adds a question mark to the beginning to help it differentiate between inputs and outputs in the text file, it then finds the input in the file and responds with one of the 3 corresponding lines below it, an example is if you input "HI" it turns it into "?HI" and then saves the 3 lines after it into an array, but this isn't working properly.. Sometimes it responds with "?HI"
#include <fstream>
#include <algorithm>
#include <iostream>
#include <ctime>
#include <string>


int main()
{
std::string input;
loop:
std::cout<<"You: ";
std::getline(std::cin, input);

if (input.empty()){
goto loop;
}
input = "?" + input;
std::fstream File("example.txt", std::ios::in);

if (File.is_open())
{
std::string line;
std::string line2;
std::string line3;
std::string line4;
int line_count = 0;

while(std::getline(File, line))
{

if (line.find(input) != std::string::npos)
{

if (std::getline(File, line2))
{
++line_count;
}
if (std::getline(File, line3))
{
++line_count;
}
if (std::getline(File, line4))
{
++line_count;
char chars[] = "!";


std::string::size_type k = 0;
while((k=line2.find('!',k))!=line2.npos) {
line2.erase(k, 1);
}
std::string::size_type q = 0;
while((q=line3.find('!',q))!=line3.npos) {
line3.erase(q, 1);
}
std::string::size_type w = 0;
while((w=line4.find('!',w))!=line4.npos) {
line4.erase(w, 1);
}
srand(time(0));
const std::string wordList[3] = { line2, line3,line4};

std::string word = wordList[rand() % 3];
std::cout << word << std::endl;
}

else
{
std::cout<<"There are no lines after that!\n";
}
}
++line_count;
}

File.close();
}
goto loop;
}
The text file contains:
?HI
!hey
!How's it going
!Hello
how do i make it so it doesn't respond with "?HI" and instead respond with only one of the 3 lines after "?HI" ?


See More: Line counting algorithm not working..?

Report •


#1
July 23, 2014 at 04:05:50
[I didn't really get what you mean]

Counting number of lines actually means count the number of new line character ('\n'), so get the code to read the file char by char till the end, if new line char is found increment var by 1 as following

#include <iostream>
#include <fstream>
using namespace std;

int main () {
char c;
int num=0;
ifstream is;
is.open ("myfile.txt");
while (is.good())
{
c = is.get();
if (c=='\n')num++;
}
is.close();
cout<<"Number of lines in file is "<<num<<endl;
return 0;
}

from: https://answers.yahoo.com/activity?...

message edited by earlpg


Report •
Related Solutions


Ask Question