Variable inside for loop - c++

I am frustrated. I am trying to find a way to get the variable called 'line' to be accessed inside of the for loop that is at the bottom of the code.
#include <ctime>
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
#include <Lmcons.h>
#include <fstream>
#include <windows.h>
using namespace std;
string currentmonth;
string earlydays;
//**************************************
string a3;
string a1;
int getdir (string dir, vector<string> &files)
{
DIR *dp;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL)
{
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
std::string fname = dirp->d_name;
if(fname.find("FIN804") != std::string::npos)
files.push_back(fname);
}
}
//***************************************
int main() {
//Copy New date to be used from date database
ifstream dailyfiledate;
dailyfiledate.open("Databasedate.txt");
string line;
if (!dailyfiledate) //checks to see if file opens properly
{
cerr << "Error: Failed to copy the first string from Date Database.";
}
else
{
if (getline(dailyfiledate, line)) // Get line
cout << line; // print the line.
dailyfiledate.close(); // Remember to close the file.
}
string dir = string(a1);
vector<string> files = vector<string>();
getdir(dir,files);
for (unsigned int i = 0; i < files.size();)
{
//cout << files[i] << endl;
a3 = files[i];
cout << a3 << endl;
string b1 = a3 + line;
cout << b1 << endl;
remove(b1.c_str());
i++;
}
}

Actually, the variable was successfully being reached inside the for loop. I guess it was an oversight on my path.
And there is absolutely no error in the code above when it's compiled.
You mo'effers really need to be more humble. Give the answer, give guidance, or don't comment at all.

Related

How do I search a string from a file and return the line location using functions in C++?

I am trying to make a program that lets me search for groups of words in a file and then it would return the line locations where they are found. I made it work for a little bit but for some reason, the value of int FileLine (line location) keeps on stacking up whenever a new word search is introduced.
include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
string S1, S2, S, Line;
int FileLine = 0;
int CountInFile(string S) {
ifstream in("DataFile.txt");
while (getline(in, Line)) {
FileLine++;
if (Line.find(S, 0) != string::npos) {
cout << "Found " << S << " at line " << FileLine << "\n";
}
}
return 0;
in.close();
}
int main()
{
// Words to search
CountInFile("Computer Science");
CountInFile("Programming");
CountInFile("C++");
CountInFile("COSC");
CountInFile("computer");
This is the output:
Is there a way that I can stop the FileLine value from stacking?

trying to add words from text file to a vector but keep getting thrown 'std::out_of_range'

trying to add words from this text file but keep getting thrown an out of range error. I think the error lies somehwere in the loops but havent been able to figure out why it isnt working. Help would be greatly appreciated
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct WordCount{
string word;
int count;
};
int main () {
vector<WordCount> eggsHam;
ifstream readFile ("NewTextDocument.txt");
int counter = 0;
int holder;
string lineRead;
WordCount word;
if(readFile.is_open()){
//add all the words into a vector
while (getline(readFile, lineRead)){
holder = counter;
for(int i = 0; i < lineRead.length(); ++i) {
if (lineRead.at(i) != ' ') {
++counter;
}
if (lineRead.at(i) != ' ') {
for (int k = 0; k < (counter - holder); ++k) {
word.word.at(k) = lineRead.at(holder + k);
}
eggsHam.push_back(word);
++counter;
}
}
}
readFile.close();
}
else cout << "Unable to open file";
return 0;
}
Your code is way to complicated. To read all words (=space-seperated thingies) into a std::vector<std::string> simply do:
#include <cstdlib>
#include <vector>
#include <string>
#include <iterator>
#include <fstream>
#include <iostream>
int main()
{
char const *filename = "test.txt";
std::ifstream is{ filename };
if (!is.is_open()) {
std::cerr << "Couldn't open \"" << filename << "\" for reading :(\n\n";
return EXIT_FAILURE;
}
std::vector<std::string> words{ std::istream_iterator<std::string>{ is },
std::istream_iterator<std::string>{} };
for (auto const &w : words)
std::cout << w << '\n';
}

Reading a File's Line with no Spaces into separate Variables

First time asking a question on this site, so here goes. I've been racking my brain for quite some time, but still can't seem to find the answer to this.
Let's say I have a file that reads as follows:
123456789John Doe 0001111.11
925219042Mary Jane 0000302.54
891492829Gertrude Marisou 0123467.76
How would I separate say, 123456789 and John into their own respective strings for input into a vector containing four variables? (Std::string, Std::string, Std::string, Double)
Here is my current code if you all would like to take a peek at it and tell me where I am going wrong.
#pragma once
#if !defined(__Account7_h__)
#define __Accoun7_h__
#include <string>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
//Personal file for trimming the extra whitespace
#include "Trim.h"
class Account7 {
private:
std::string account_code;
std::string first_name;
std::string last_name;
double balance;
public:
//Getters, Setters, Initialization List and whatnot.
//On a separate file
#if !defined(__Vmanager7_h__)
#define __Vmanager7_h__
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include "Account7.h"
#include "Trim.h"
using namespace generic;
class Vmanager7 {
public:
int a = 1;
std::ifstream infile;
std::ofstream outputFile;
std::vector<Account7> _Account;
Account7 temp;
std::string Empl;
std::string scapeg;
std::string acc_c;
std::string fname;
std::string lname;
double bal;
int Managed() {
int count;
infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
infile.open("account.dat", std::ifstream::in);
}
catch (std::ios_base::failure &fail) {
std::cout << "File is not opening" << std::endl;
return 0;
}
infile.exceptions(std::ios::goodbit);
while (getline(infile, Empl)) {
count = 1;
std::istringstream ss(Empl);
while (getline(ss, scapeg)) {
if (count == 1)
acc_c = scapeg;
else if (count == 2)
fname = scapeg;
else if (count == 3)
lname = scapeg;
else
bal = atof(scapeg.c_str());
count++;
}
temp.setac(acc_c);
temp.setfn(fname);
temp.setln(lname);
temp.setba(bal);
_Account.push_back(temp);
}
infile.close();
outputFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
outputFile.open("Aoutput.dat");
}
catch (std::ios_base::failure &fail) {
std::cout << "File opening fail" << std::endl;
return 0;
}
outputFile.exceptions(std::ios::goodbit);
for (int i = 0; i < _Account.size(); i++) {
std::cout << _Account[i].getac() << " " << _Account[i].getfn() << " " << _Account[i].getln() << " " << _Account[i].getba();
bal = _Account[i].getba();
bal -= int(bal);
if (bal == 0)
std::cout << ".00";
std::cout << '\n';
}
outputFile.close();
}
};
};
The output I get is something along the lines of this:
123456789John Doe 0001111.11 -9.25596e+61
925219042Mary Jane 0000302.54 -9.25596e+61
191492829Gertrude Marisou 0123467.76 -9.25596e+61
I would like the output to look just like the input. Any help would be immensely appreciated.

Text-to-speech pass string to speak

Iā€™m new in programming, so need your help, just trying to make program with Text to Speech C++ in Visual Studio 2015 on Windows 10 using Speech Synthesizer object in a CLR Console application. But I can't figure out, how to get line through the variable "t" to speak not only synth->Speak("Line saved"); and synth->Speak("Line exist"); , but with "t" like this: "Line (text line) exist". So how can I pass a string to the Speak function?
Can you help me figure out:
#include "stdafx.h"
#include <conio.h>
#include <Windows.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using namespace System;
using namespace System::Speech::Synthesis;
using namespace System::IO;
const string FILE_NAME = "lines.txt";
vector<string> getFileLines(string file) {
ifstream in(FILE_NAME);
vector<string> lines;
for (string line; getline(in, line); ) {
lines.push_back(line);
}
return lines;
}
string getUserInput() {
string str;
getline(cin, str);
return str;
}
int main()
{
vector<string> lines = getFileLines(FILE_NAME);
ofstream fileOut(FILE_NAME, ios::app);
for (int n = 0; n < 10; n++)
{
cout << "Write: > ";
std::string t = getUserInput();
auto it = std::find(lines.begin(), lines.end(), t);
if (it == lines.end()) {
fileOut << t << endl;
lines.push_back(t);
cout << "Line \"" << t << "\" saved.\n";
SpeechSynthesizer^ synth = gcnew SpeechSynthesizer();
synth->Speak("Text saved");
}
else
{
cout << "LIne \"" << t << "\" exist.\n";
SpeechSynthesizer^ synth = gcnew SpeechSynthesizer();
synth->Speak("Line exist");
}
}
cout << endl;
getUserInput();
return 0;
}
and this way with marshal:
#include "stdafx.h"
#include <conio.h>
#include <Windows.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <msclr\marshal_cppstd.h>
using namespace msclr::interop;
using namespace std;
using namespace System;
using namespace System::Speech::Synthesis;
using namespace System::IO;
const string FILE_NAME = "lines.txt";
vector<string> getFileLines(string file) {
ifstream in(FILE_NAME);
vector<string> lines;
for (string line; getline(in, line); ) {
lines.push_back(line);
}
return lines;
}
string getUserInput() {
string str;
getline(cin, str);
return str;
}
int main()
{
vector<string> lines = getFileLines(FILE_NAME);
ofstream fileOut(FILE_NAME, ios::app);
for (int n = 0; n < 10; n++)
{
cout << "Write: > ";
std::string t = getUserInput();
auto it = std::find(lines.begin(), lines.end(), t);
if (it == lines.end()) {
fileOut << t << endl;
lines.push_back(t);
cout << "Line \"" << t << "\" saved.\n";
String^ str = marshal_as<String^>(str);
std::string line = "Line " + t + " exists!";
synth->Speak(marshal_as<String^>(line));
}
else
{
cout << "LIne \"" << t << "\" exist.\n";
String^ str = marshal_as<String^>(str);
std::string line = "Line " + t + " exists!";
synth->Speak(marshal_as<String^>(line));
}
}
cout << endl;
getUserInput();
return 0;
}
I got this errors:
Error C4996
'msclr::interop::error_reporting_helper<_To_Type,_From_Type,false>:ā€Œā€‹:marshal_as':
This conversion is not supported by the library or the header file
needed for this conversion is not included.
Error C2065 '_This_conversion_is_not_supported': undeclared identifier
X_TTS2 c:\program files (x86)\microsoft visual studio
14.0\vc\include\msclr\marshal.h 219
Per the documentation:
marshal_as
If you try to marshal a pair of data types that are not supported, marshal_as will generate an error C4996 at compile time. Read the message supplied with this error for more information. The C4996 error can be generated for more than just deprecated functions. One example of this is trying to marshal a pair of data types that are not supported
The supported conversions are documented:
Overview of Marshaling in C++
The marshal_as() function supports marshaling a std::string to a System::String^ if you use marshal_cppstd.h, which your example does:
#include <msclr\marshal_cppstd.h>
std::string line = "Line " + t + " exists!";
synth->Speak(marshal_as<String^>(line));
So the error you show does not make sense, unless it is referring to this statement:
String^ str = marshal_as<String^>(str);
You are trying to marshal a String^ to a String^, which is not a supported marshal conversion. Also, using a variable in the same statement that declares it is undefined behavior anyway, so you need to remove the statement completely as it is useless.
Alternatively, marshal_as() supports marshaling a const char* if you use marshal.h:
#include <msclr\marshal.h>
std::string line = "Line " + t + " exists!";
synth->Speak(marshal_as<String^>(line.c_str()));

List Iterator Not incrementable - Runtime Error

I am getting a List Iterator Not incrementable on the code below after adding a stringstream for movieName and am unsure as how to go about solving the error. I am trying to read in from a file and add the items into a list then itterate through the list and add eash word from the title of the movie into another list. Any help would be appreciated!
#include <iostream>
#include <string>
#include <list>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
list <string> movieList;
list <string>::iterator iterMovie;
list <string> *titleWordList = new list <string>;
list <string>::iterator iterTitleWord;
ifstream inFile;
inFile.open("JamesBond.txt");
if (!inFile)
{
cout << "Could not find the specified file.";
}
else
{
movieList.clear();
string movieName;
while(getline(inFile,movieName))
{
movieList.push_back((movieName));
/*
for each(string movieName in movieList)
{
titleWordList->push_back(movieName);
}
*/
stringstream ss(movieName);
while (ss >> movieName)
{
titleWordList->push_back(movieName);
}
}
}
if (movieList.empty())
{
cout << "No Data Found!" << endl;
}
else
{
cout << "Writing Output: \n\n";
for (iterMovie=movieList.begin(); iterMovie !=movieList.end(); ++iterMovie)
{
cout << *iterMovie << endl;
}
for (iterTitleWord=movieList.begin(); iterTitleWord != movieList.end(); ++iterMovie)
{
cout << *iterTitleWord << endl;
cout << &titleWordList;
}
}
}
In the second for there is a copy paste error, it should be ++iterTitleWord instead of ++iterMovie.
Also, as #Greg suggested, iterTitleWord=movieList.begin() and iterTitleWord != movieList.end() should be iterTitleWord=titleWordList->begin() and iterTitleWord != titleWordList->end() respectively.