Why does my program act different every time? - c++

I'm trying to do a console version of the game "I packed my suitcase...".
The basic idea is that i have a .txt file with about 4.3k random nouns in it, one word per line. I want to read out the words from this file and put them into a vector<string>. Next steps would be to have another vector with the words that the player has to keep in mind and so on.
But I struggle on a very early stage right now.
What happens almost every time I run the code is that it just stops right after the line "Computer always starts. Have fun!" is printed to the console. However, I tried multiple cout statements in the end and I used to get some values. But they were always different. E.g ranging from 0 to 4308 (the exact number of lines) when printing vector.size(). In the last 30 minute the program never reached one of the couts.
Using Clion 2016.1.1 with CMake 3.5.1 bundle under linux mint
access to file.txt is not restricted in any way
the path for file.txt is correct
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "player.h"
using namespace std;
int main() {
int player_score;
string player_name;
string line;
vector <string> words_list;
ifstream file;
file.open("/home/rainbowterminal/ClionProjects/PackingBags/file.txt", ios_base::in);
if(!file)
{
cerr << "Couldn't open file" << endl;
}
else
while (getline(file, line))
{
words_list.push_back(line);
}
file.close();
Player *player;
player = new Player;
cout << "Hey and welcome to 'I packed my suitcase and take with me'. You won't beat it. Promise." << endl;
cout << "To start playing just enter your name" << endl;
cin >> player_name;
player->set_name(player_name);
cout << "Okay " << player->get_name() << ", let's do this! You're a playing 'I packed my suitcase and take with me" << endl;
cout << "against the computer. Just repeat the words printed to the console" << endl;
cout << "and add an own word in the end. DO NOT seperate by commata. Letter case" << endl;
cout << "doesn't matter. Computer always starts. Have fun! " << endl;
//srand ((unsigned int) time(NULL));
//int random = (int) (rand() % words_list.size());
cout << words_list.size();
cout << words_list[100];
cout << player->get_name();
//vector<string> used_words;
//used_words.push_back(words_list[randomIndex]);
return 0;
}
As suggested i broke it down to the basic problem. What happens with this piece of code is that
cout << words_list.size();
only returns the size of the vector in only 50% of the trys.
int main() {
string line;
vector <string> words_list;
ifstream file;
file.open("/home/rainbowterminal/ClionProjects/PackingBags/file.txt", ios_base::in);
if(!file) {
cerr << "Couldn't open file" << endl;
}
else {
while (getline(file, line)) {
words_list.push_back(line);
}
}
file.close();
cout << words_list.size();
}
file.txt
If anybody could me give me a hint what I did wrong I'd be more than happy to work this out on my own.

Related

Way to deal with multiple user arguments in C++?

Task Commands Picture Ok, I've progressed a bit more from my previous work but I just can't get past this issue which probably isn't that big. My task, which is basically a text file editor, requires multiple user arguments after the program begins running, ranging from let's say 1 such as "details" to 3 or 4 with random user input like display x y or savepart x y (see attached image). My code currently takes in the first line the user inputs using cin and getline but it can only read known strings such as load userinput.txt (which is the filename), and quit and I don't know how I can store the user's entered values for variables. How do I solve this?
What basically needs to probably change is the getline under the while loop or what's written in the if statements but I've tried everything.
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
string secondword;
string fword;
string line;
ifstream myfile;
fstream fFile;
bool running = true;
int x;
int length;
int main(int argc, char* argv[]) {
while (running) {
getline(cin, fword); //Reads first line user inputs
//if first word equals laod command load file to memory
if (fword == "load userinput.txt") {
ifstream myfile("userinput.txt", ifstream::binary);
myfile.seekg(0, myfile.end); //Searches till end of file
length = myfile.tellg(); //Sets length as total number of chars in file
myfile.seekg(0, myfile.beg); //Searches from the beginning
char* buffer = new char[length]; //Allocates file memory to pointer
cout << "Reading " << length << " characters... " << endl;
myfile.read(buffer,length); //reads file and compares buffer size with legnth size
if (myfile)
cout << "All characters read and stored in memory sucessfully" << endl;
else
cout << "error: only " << myfile.gcount() << " can be read" << endl;;
myfile.close();
}
//Quit
if (fword == "quit") {
running = false; //Breaks while loop statement
cout << "User has quit the program" << endl;
}
//Clear all lines in text
if (fword == "clear all") {
fFile.open("userinput.txt", ios::out | ios::trunc);
fFile.close();
cout << "All lines have been cleared" << endl;
}
//Display All Text
if (fword == "display text") {
myfile.open("userinput.txt", ios::in);
while (getline(myfile, line)) { //read data from file object and put it into string.
cout << line << endl; //print the data of the string
}
}
}
return 0;
}

ifstream doesn't seem to open an external exe for reading and writing

I am a beginner hobby programmer.
I am working on a small program that will take the FEN string of any chess position from the user, pass it into the Stockfish chess engine, and grab a move output from the exe once it has done its magic in finding a move.
The problem is, once I enter the FEN string into my compiled program, the command line window remains static, and outputs nothing. When I press enter, new lines simply appear, and when I enter anything other than spaces, the command line window closes.
I tried opening Task manager to check to see if Stockfish was running after the FEN string was entered, and I couldn't find it anywhere, which must mean Stockfish wasn't opened by my program to begin with.
The following code has been compiled with g++ in Windows smoothly with no error messages to be found.
After doing some research online, I have tried changing "Stockfish.exe" to "C:....(path)..\Stockfish.exe" to no avail (with loads of compilation errors too).
Am I missing something? What must I do in order for the program to actually open Stockfish and enter the FEN and UCI commands?
Many thanks!
^_^
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
int main() {
cout << "Welcome to the Chess Puzzle Solver 1.0!" << endl;
cout << "Please enter the FEN string of the position you'd like to solve." << endl;
cout << "" << endl;
cout << "Example: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" << endl;
cout << "[The starting position] ^" << endl;
cout << "" << endl;
string userStartingFEN;
cin >> userStartingFEN;
// Opening Stockfish to do the main stuff!
ifstream inFile;
ofstream outFile;
inFile.open("Stockfish.exe", ios::in | ios::out);
outFile.open("Stockfish.exe", ios::in | ios::out);
string uciCommand1;
uciCommand1 = "uci";
string uciCommand2;
uciCommand2 = "setoption name Threads value 4";
string uciCommand3;
uciCommand3 = "setoption name Contempt value 0";
string uciCommand4;
uciCommand4 = "setoption name Hash value 64";
cin >> uciCommand1;
cin >> uciCommand2;
cin >> uciCommand3;
cin >> uciCommand4;
cout << "I will say this if the parameters were set." << endl;
// Entering the user's wanted position
string inputtingFEN;
inputtingFEN = "position fen ";
cin >> inputtingFEN >> userStartingFEN;
string checkMe;
checkMe = "UCI and Position all set!";
cout << checkMe << endl;
inFile.close();
outFile.close();
return 0;
}

How Do I read and Output the Contents of a File and the Number of Words it Contains?

I am attempting to write a program for homework which reads the contents of a notepad file and displays the contents and the number of words int he file. My code currently outputs nothing when I enter the name of the names of files I am using to test the program, and the input validation while loop I inserted does not function either.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//Declare needed variables
string fileName, contents;
int wordCount = 0;
ifstream inData;
//Display program info
cout << "*** A SIMPLE FILE PROCESSING PROGRAM ***" << endl;
//Prompt user input
cout << "Enter a filename or type quit to exit: ";
cin >> fileName;
inData.open(fileName.c_str());
//Inform the user when their input is invalid and ask them to input another
file name
while (!inData)
{
inData.clear();
inData.ignore(200, '\n');
cout << "File not found. Please type a correct file name." << endl;
cin >> fileName;
inData.open(fileName.c_str());
}
inData >> contents;
//Read and output the contents of the selected file
while (inData)
{
cout << fileName << " data\n";
cout << "***********************" << endl;
inData >> contents;
wordCount++;
cout << contents << endl;
inData >> contents;
}
//Display the number of words in the file
cout << "***********************" << endl;
cout << fileName << " has " << wordCount << " words." << endl;
inData.close();
return 0;
}
The code compiles in its current state [but does not produce the desired outcome.
I will show you one of the many possible solutions.
But I would not recomend, to check the validity of a filename in a loop. You will give the user no chance to escape. Hence, I propose to open the file, and, if that does not work, show an error message and quit.
Then, what sounds easy in the beginning like, count the words, is not really that easy. What is a word? Characters only, or characters mixed with digits or even an underscore in it like for C++ variable names? Needs to be defined.
Additionally you may have separators like commas or one and more other white spaces. So a line like "Hello,,,,World" cannot be so easily counted. If you try to read the 2 words, then you will see a surprise.
std::string s1{};
std::string s2{};
std::istringstream iss("Hello,,,,World");
iss >> s1 >> s2;
Will read everything in s1!
The solution is that we define clearly what a word is. And this we will do with a std::regex. In the below example we use characters, digits and _
Then we use the regex_iterator to find all occurences of the regex (the word) in the line. We substract the end from the beginning with std::distance, which will give us the count of the words.
Then we give an output to the user in whatever format.
It may seem complicated. But it is precise. And rather flexible. Try to anaylze line by line and you will understand it.
Please see:
#include <iostream>
#include <string>
#include <regex>
#include <fstream>
#include <iomanip>
int main()
{
// Get a filename from the user
std::cout << "Enter a filename:\n";
std::string filename{}; std::cin >> filename;
// Try to open and read the file
std::ifstream fileStream(filename);
if (fileStream) {
// We will count all words
size_t numberOfWordsOverall{ 0 };
// We will also count the lines in the file
size_t lineCounter{ 1 };
// Define, what a word is. In this case: Characters, Digits and _
std::regex regexForWord("[\\w\\d_]+");
// Read all lines in file
std::string line{};
while (std::getline(fileStream, line)) {
// Count the numbers of words in one line
const size_t numberOfWordsInLine = std::distance(
std::sregex_token_iterator(line.begin(), line.end(), regexForWord, 1),
std::sregex_token_iterator()
);
// Update the overall word counter
numberOfWordsOverall += numberOfWordsInLine;
// Show result to user
std::cout << "# " << std::left << std::setw(2) << lineCounter++ << " (Words in line: "<< std::setw(2) << numberOfWordsInLine <<
" Words overall: " << std::setw(4) << numberOfWordsOverall << ") Line content --> " << line << '\n';
}
}
else {
std::cerr << "Could not open file '" << filename << "'\n";
}
return 0;
}
Hope this helps . . .

C++ Searching CSV file from inputted string

I am trying to create a program that will load the CSV file and based upon the inputted word search through the file and return any lines that contain the word. The CSV file is a mass download of tweets and has the following columns:
Date & Time Created
The Tweet
The tweets are also surrounded by b'TWEET TEXT HERE' so would need to remove the b' ' from when it printed out. I am unable to change anything to do with the CSV file sadly so cant manually remove it. The issues I am having are:
Listing the total amount of tweets within the file the program just freezes
Removing the b' ' from the tweets
The else statement causes "not found" to be constantly printed
Code I currently have that is returning the tweets that contain the inputted word but also the false positive.
The current output when running the below code
#include "stdafx.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string token;
ifstream fin;
fin.open("sampleTweets.csv");
if (fin.is_open())
{
cout << "File opened successfully" << "\n";
}
else {
cout << "Error opening file" << "\n";
}
cout << "Enter search word: ";
cin >> token;
"\n";
string line;
while (getline(fin, line)) {
if (line.find(token) != string::npos) {
cout << line << endl;
} else {
cout << token << " not found" << endl;
}
}
fin.close();
char anykey;
cout << "press any key";
cin >> anykey;
return 0;
}
Code I was using for counting total tweets
int count = 0;
char str[140];
while (!fin.eof())
{
fin.getline(str, 140);
count++;
}
cout << "Number of lines in file are " << count;
Any help on this would be amazing as I am quite new to C++ and not sure where to go from here!
You can remove the "b" with erase:
if (line.find(token) != string::npos){
int n= line.find(",");
line.erase(n+1, 3);
cout << line << endl;
}
and you can count the lines inside the while loop:
int count = 0;
while (getline(fin, line)) {
++count;
...
}
EDIT: you can remove the extra quotes and commas like so:
line[n] = ' '; // change comma int space
line.erase(n+1, 4); // remove "b""
line.resize(line.size()-5); // remove trailing """,,

Why can't I write to a file if it is located within an if statement?

I am trying to create a very simple program that writes to a file, but can't understand why it won't let me write to a file if I put it within an if statement! Here's the code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void readFile();
int main()
{
string line;
string today;
string readOrWrite;
cout << "Do you want to write to a file or read a file? " << endl;
cout << "Type \"write\" or \"read\" ";
cin >> readOrWrite;
if (readOrWrite == "read")
{
readFile();
}
else if (readOrWrite == "write")
{
cout << "How are you today? " << endl;
getline(cin, today);
ofstream myJournal;
myJournal.open("Journal.txt", ios::app);
myJournal << today << " ";
myJournal.close();
}
else
{
return 0;
}
return 0;
}
void readFile()
{
ifstream myJournal;
myJournal.open("Journal.txt");
string line;
if (myJournal.is_open())
{
while (getline(myJournal, line))
{
cout << line << endl;
}
myJournal.close();
}
else
{
cerr << "Error opening file ";
exit(1);
}
}
When I move it out of the if statement, it works smoothly and is able to write to the file, but when I place it inside, it opens the program, asks me the "Do you want to write to a file or read a file? ", I type "write", then it says "How are you today? " and then ends the program, printing "Press any key to continue...". Any help?
it says "How are you today? " and then ends the program, printing "Press any key to continue...". Any help?
std::istream::ignore should help in that case you are encountering.
cout << "How are you today? " << endl;
cin.ignore(10, '\n'); // Inserted
getline(cin, today);
Why do we need that in between?
It takes out 10 characters, which is enough amount of length, from the buffer and stops if it encounters a newline, which is '\n'. (Remember that you press the key 'enter' after typing "wrtie")
By doing so you can move on to the next new line, preventing std::cin from any parse failure.
More info : http://www.cplusplus.com/reference/istream/istream/ignore/