Data from table into C++ quiz application - c++

I wrote a code which shows a question and 4 answers, ask to choose the correct one, and checks the choice.
Now I would build a table which would contain 6 columns: question/a/b/c/d/correct_answer, and about hundred of lines with my questions. Now I would like my program to randomly choose 5 of a question from table and show it to user.
First question is, can I do my table in Excel and use it than in Visual Studio? If not, what software should I use to do table like this as simply as possible, and how to implement it into my Visual studio project? If yes, how to implement Excel table to my Visual studio project?
Second question is, what simplest code should I write to randomly choose 5 of 100 question from my table?
A code of a question is:
int main()
{
string ans; //Users input
string cans; //Correct answer, comes from table
string quest; //Question, comes from table
string a; // Answers, come from table
string b;
string c;
string d;
int points; //Amount of points
points = 0;
cout << "\n" << quest << "\n" << a << "\n" << b << "\n" << c << "\n" << d << "\n";
cout << "Your answer is: ";
cin >> ans;
if (ans == cans)
{
points = points + 1;
cout << "Yes, it is correct\n";
}
else
{
cout << "No, correct answer is " << cans << "\n";
}
return 0;
}

First Part
You can definitely use Excel to edit your questions and save them. But when you save it, pay attention to the file format.
You want to save your Excel file as a .csv file instead of .xls or .xlsx file. Just go to File -> Save File As -> and change type to .csv.
This is because, reading .csv files is a lot easier. .csv files have each cell in row separated by a comma (,) and each row by a newline ('\n') character.
So, here is a sample Excel file:
After I save it as a .csv file and open it using a text editor (Atom, here), it looks like this:
After, that you only need to write some code to read the file.
This is the code I used (I've added excessive comments to make the code more explicit for beginners):
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
const int MAX_QUESTIONS = 3;
const int COLUMNS = 6; //Question, Options A, B, C, D, Correct Answer
int main() {
ifstream fp;
fp.open("test.csv");
//If file could not be opened
if (fp.fail()) {
std::cout << "failed to open file" << std::endl;
return 1;
}
//Create a 2D vector of strings to store the values in the file
vector< vector<string> > table;
string line;
//Loop through the entire file (fp)
//Store all values found until I hit a newline character ('\n') in the string line
//This loop automatically exits when the end-of-file is encountered
while (getline(fp, line, '\n')) {
//Create an temporary vector of strings to simulate a row in the excel file
vector<string> row;
//Now I am passing in this string into a string stream to further parse it
stringstream ss;
ss << line;
string part;
//Similar to the outer loop, I am storing each value until I hit a comma into the string part
while (getline(ss, part, ',')) {
//Add this to the row
row.push_back(part);
}
//Add this row to the table
table.push_back(row);
}
//Print out the entire table to make sure your values are right
for (int i = 0; i <= MAX_QUESTIONS; ++i) {
for (int j = 0; j < COLUMNS; ++j) {
cout << table[i][j] << " ";
}
cout << endl;
}
return 0;
}
Second Part
To choose a random number, you can use this code (I borrowed it from another answer)
#include <random>
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased
auto random_integer = uni(rng);
Unlike the old method, this doesn't create bias towards the lower end. However, the new engine is available only in C++11 compilers. So keep that in mind. If you need to use the old method, you can correct the bias by following this answer.
To choose 5 different numbers, each time you generate a random number store it in an array and check whether this number has already been used. This can prevent repetition of questions.

To answer question 1: In Excel, click File>Save As. Choose UTF-16 Unicode Text (.txt), name your file, and save it where your program can access it. In your C++ program, use the fstream library for text files:
#include <fstream>
With the text file in the same directory, use
ifstream fin;
fin.open("FILENAME.txt");
.
.
.
fin >> variable;
.
.
.
fin.close();
To answer question 2: There is a rand() function that returns an integer between zero and RAND_MAX. Then you can use modulus(%) to get a random number in the desired range.
#include <cstdlib> // for srand() and rand()
#include <ctime> // for time()
.
.
.
srand(time(NULL)); // seed the RNG on seconds
.
.
.
var = rand() % ONE_MORE_THAN_MAX;
Here's a quizzer I made to help myself study:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
const char QUESTIONS_FILE_NAME[] = "questions.dat";
const char QUESTION_ANSWER_SEPARATOR = ',';
const char QUESTION_SEPARATOR = '\n';
const short MAX_QUESTION_LENGTH = 300;
const short MAX_ANSWER_LENGTH = 300;
const short MAX_NUM_QUESTIONS = 300;
int main()
{
char questions[MAX_NUM_QUESTIONS][MAX_QUESTION_LENGTH];
char answers[MAX_NUM_QUESTIONS][MAX_ANSWER_LENGTH];
short counter = 0;
short question_choice;
char user_answer[MAX_ANSWER_LENGTH];
ifstream fin;
fin.open( QUESTIONS_FILE_NAME );
srand(time(NULL));
while(fin.getline( questions[counter], MAX_QUESTION_LENGTH-1,
QUESTION_ANSWER_SEPARATOR ))
{
fin.getline( answers[counter], MAX_ANSWER_LENGTH-1,
QUESTION_SEPARATOR );
counter++;
}
fin.close();
cout << endl << "Press CTRL+C to quit at any time" << endl << endl;
while ( counter > 0 )
{
question_choice = rand() % counter;
cout << endl << questions[question_choice] << " ";
cin >> user_answer;
if ( strcmp( user_answer, answers[question_choice] ) )
{
cout << endl << "Incorrect" << endl
<< "It was " << answers[question_choice] << endl;
strcpy( questions[counter], questions[question_choice] );
strcpy( answers[counter], answers[question_choice] );
counter++;
}
else
{
cout << endl << "Correct" << endl;
counter--;
strcpy( questions[question_choice], questions[counter] );
strcpy( answers[question_choice], answers[counter] );
}
}
cout << endl << "You Win!!!!" << endl;
return 0;
}
questions.dat would have data like this
In what year was the Pendleton Civil Service Reform Act enacted?
a.1873
b.1883
c.1893
d.1903,b
In what year did Hurricane Katrina occur?
a.2001
b.2003
c.2005
d.2007,c

Related

converting a random line from a text file into numbers and then outputting the numbers, with the user having to guess the original line

I'm creating a piece of code which is supposed to simulate a guessing game in which I pull a random line from a text file, in this example "premier league football teams", then I have to take the random line and have it convert into the corresponding numbers in the alphabet, so in the example of "arsenal" I would have to output "1 18 19 5 14 1 12". as this is a game the user has to guess that the numbers mean "arsenal" and then type that in to gain a point and continue. so far I have been able to code a method of pulling a random line from the file, however I am unsure how I would be able to then convert that code into numbers without outputting the answer, as this is meant to be a guessing game.
this is the relevant section of text, but to keep this short I will not paste the full code
vector<string> lines;
srand(time(NULL));
//ensures random selection on each new code run
ifstream file("Premier_League_Teams.txt");
//pulls the file from the directory
int total_lines = 0;
while (getline(file, line))
//this function counts the number of lines in a text file
{
total_lines++;
lines.push_back(line);
}
int random_number = rand() % total_lines;
//selects a random entry from the text file
//end of adapted code
cout << lines[random_number];
I am assuming that I will have to do a switch statement, but I do not know how to apply that case statement to the randomly selected line, and then have the user input the plain english text
NEW CODE WITH HELP FROM COMMENTS
#include <fstream>
//fstream included to pull answers from category files
#include <string>
#include <vector>
#include <list>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
cout << "Richard Osman's house of Games: This round is in code.\n\n\n";
cout << "The objective of this round is to unscramble the coded word, you will be given the category as the clue and you have to type out what you belive the answer to be, with a capital letter\n\n";
cout << endl;
string Name;
cout << "But First, Enter your first name.\n";
cin >> Name;
cout << "Welcome contestant " << Name << " Are you ready to begin the quiz?\n";
// this is to add a level of immersion to the game, by allowing the code to recall the players name so that they have a personalised experience
string respond;
cout << "please type Yes or No (case sensitive).\n";
cin >> respond;
if (respond == "Yes")
{
cout << "\nGood luck!";
}
else
{
cout << "Maybe next time!";
return 0;
}
{ cout << "The first category is..." << endl;
cout << "Premier League Football Teams!" << endl;
//code adapted from Ranjeet V, codespeedy
string line;
vector<string> lines;
srand(time(NULL));
//ensures random selection on each new code run
ifstream file("Premier_League_Teams.txt");
//pulls the file from the directory
int total_lines = 0;
while (getline(file, line))
//this function counts the number of lines in a text file
{
total_lines++;
lines.push_back(line);
}
int random_number = rand() % total_lines;
//selects a random entry from the text file
//end of adapted code
int random_number = 0;
vector<string> lines;
lines.push_back("abc arsenal");
string alpha = "abcdefghijklmnopqrstuvwxyz";
string word = lines[random_number];
//line from lines vector for which we will calculate numbers
int* codes;
codes = new int[word.length()];
//array in which we will store codes for letters
for (int i = 0; i < word.length(); i++) {
//iterate over each characte of string word
if (word[i] != ' ')
//as we dont want to replace spaces with numbers or somethings, but it will automatically become 0 as it is default
codes[i] = alpha.find(word[i]) + 1;
//assign codes correspoding element to (index of char)+1
}
for (int i = 0; i < word.length(); i++) {
if (codes[i] == 0) {
continue;
//do not print codes' element if it is zero because it will become zero for spaces
}
cout << codes[i] << " ";
//outputting each codes element with a space in between
}
You can declare a string like
std::string alphabet="abcdefghijklmnopqrstuvwxyz"; and then for particular character if you want to find the equivalent position number you can use str.find(char); to get index of char in str and then add one to get its position number.
For eg;
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int random_number=0;
vector<string> lines;
lines.push_back("abc arsenal");
string alpha="abcdefghijklmnopqrstuvwxyz";
string word=lines[random_number]; //line from lines vector for which we will calculate numbers
int* codes;
codes=new int[word.length()]; //array in which we will store codes for letters
for(int i=0;i<word.length();i++) { //iterate over each characte of string word
if(word[i]!=' ') //as we dont want to replace spaces with numbers or somethings, but it will automatically become 0 as it is default
codes[i]=alpha.find(word[i])+1; //assign codes correspoding element to (index of char)+1
}
for(int i=0;i<word.length();i++) {
if(codes[i]==0) {
continue; //do not print codes' element if it is zero because it will become zero for spaces
}
cout<<codes[i]<<" "; //outputting each codes element with a space in between
}
}
[Note] : Just for example I have assigned random_number to 0 and made a sample vector lines so that you can have more clarity on how to use this method in your case.
the char datatype have a numerical value and are displayed as a character. We make use of this!
Lowercase a = 97, lowercase b = 98, etc. So if you subtract 96 and then cast it to an interger using (int), you will be all set :)

Why am I getting a timeout(using sstream to parse list of integers separated by commas)?

I am given an input string of n integers, separated by commas (e.g. "23,4,56"). I need to set a stringstream to represent this string and then use it to scan each integer into a vector. The elements of the vector (the integers in the list) will end up being output line by line. I am given the main(), and am simply responsible for writing parseInts(string str). For some reason, I keep getting a timeout. I'm guessing it's something in my while loops, specifically concerning how I am manipulating my sstream with str(), but I can't figure out exactly what is going on. I am new to sstream and C++ so any help would be appreciated!
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
int a; //will use this to hold the value of the 1st int in the sstream
stringstream list_initial; //will iterate over this sstream
list_initial.str(str); //set sstream to represent input str
vector<int> list_final; //will return this final vector for output in main
while (!list_initial.str().empty()){ //stop iterating at end of string
list_initial>>a; //store leading int value in a
list_final.push_back(a); //add a to end of vector
while (!ispunct(list_initial.str()[0])){ //get to next int in list
list_initial.str(list_initial.str().erase(0,1));
};
list_initial.str(list_initial.str().erase(0,1)); //erase leading comma
};
return list_final;
};
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
Your function implementation could be really improved, but following your logic, if you replace the second while line:
while (!ispunct(list_initial.str()[0])){ //get to next int in list
by this one, adding a length check:
while (list_initial.str().size() && !ispunct(list_initial.str()[0])){ //get to next int in list
, then is runs, works well and exits well.
Explanations
This loop was never breaking, because at the end of the process, ispunct() function was never recognizing its parameter, !list_initial.str()[0], as something true : the string list_initial.str() is empty at this moment, then the 0 index doesn't exist.
Please look at the doc on cplusplus.com:
If pos is equal to the string length, the const-version never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.
Your program was freezing because it didn't found the right condition which could have leaded to leaving the above loop.
Advices
One important thing to talk about your question is : why didn't you find the answer yourself ? One answer for this question is the following : you didn't try to debug your code.
To answer your question, I just debugged your code, and found quickly the problem just by adding this kind of lines around your code, to see what happened:
cout << "list_initial: " << list_initial.str() << endl;
An example for your code, with debug statements added::
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
cout << "begin parseInts()" << endl; // ###### DEBUG ######
int a; //will use this to hold the value of the 1st int in the sstream
stringstream list_initial; //will iterate over this sstream
list_initial.str(str); //set sstream to represent input str
vector<int> list_final; //will return this final vector for output in main
cout << "begin while 1" << endl; // ###### DEBUG ######
while (!list_initial.str().empty()){ //stop iterating at end of string
list_initial >> a; //store leading int value in a
list_final.push_back(a); //add a to end of vector
cout << "a: " << a << endl; // ###### DEBUG ######
cout << "begin while 2" << endl; // ###### DEBUG ######
while (!ispunct(list_initial.str()[0])){ //get to next int in list
cout << "list_initial: " << list_initial.str() << endl; // ###### DEBUG ######
list_initial.str(list_initial.str().erase(0,1));
};
cout << "endwhile 2" << endl; // ###### DEBUG ######
list_initial.str(list_initial.str().erase(0,1)); //erase leading comma
};
cout << "endwhile 1" << endl; // ###### DEBUG ######
cout << "end parseInts()" << endl; // ###### DEBUG ######
return list_final;
};
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
cout << "begin for" << endl; // ###### DEBUG ######
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
cout << "end for" << endl; // ###### DEBUG ######
return 0;
}
This (very basic) debugging technic permits you to quickly find out a bug in your code; just add some cout << ... << endl; lines inside the code to point out some important informations, i.e.: "Which loop is causing freezing?", or "What is the content of this variable at this moment?".
If you put cout << "Entering While loop 1" << endl; before, and cout << "Exiting While loop 1" << endl; after each suspected loop, you may learn many things about what happens during the execution of your program.
With this debugging lines added, you can easily find out that the second loop is looping forever; then you can narrow your bug investigation to this loop.
A stream is an abstract file. It is just a bunch of text that can be understood by things like, for example, cin >> n to convert numbers to integers.
Here's an idea of how to use a stream:
#include <cctype>
#include <ciso646>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
vector<int> parse_ints( const string& s )
{
vector<int> ints; // resulting list of ints
istringstream ss(s); // stream of ints separated by (non-digits)
int n; // each int extracted from the stream
// while input an int
while (ss >> n)
{
// save the int
ints.push_back(n);
// skip to next digit
while (ss and !isdigit(ss.peek())) ss.get();
}
return ints;
}
int main()
{
vector<int> xs = parse_ints( "2, 3 ,5; 7 : 11.13\t17abc21" );
for (int x : xs)
cout << x << " ";
cout << "\n";
}
This produces:
2 3 5 7 11 13 17 21
Notice how we can simply skip characters we aren't interested in? In this particular case, we skip all non-digit characters.
Hope this helps.

C++ loading numbers from a file then finding the sum

I posted something on this last night, but I have decided to change my approach slightly as I wasn't fully understanding the code I was trying to use.
I apologise as I know this topic has been done to death but I'd like a little help with the code I've written.
I'm loading a .txt file from my computer with 100 integers in. They are each on new lines.
This is my code so far:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main ()
{
ifstream fout;
ifstream fin;
string line;
ifstream myfile ("100intergers.txt");
if (myfile.is_open())
{
while ( getline(myfile,line) )
{
cout << line << '\n';
}
// Closes my file
myfile.close();
// If my file is still open, then show closing error
if (myfile.is_open())
cerr << "Error closing file" << endl;
exit(1);
}
int y = 0;
int z = 0;
int sum = 0;
double avg = 0.0;
avg = sum/(y+z);
cout << endl << endl;
cout << "sum = " << sum << endl;
cout << "average = " << avg << endl;
// checking for error
if (!myfile.eof())
{
cerr << "Error reading file" << endl;
exit(2);
}
// close file stream "myfile"
myfile.close();
return(0);
}
When I run it I get exit code 1 (as well as a list of my 100 integers).
Which means my if clause isn't the right choice, what's a better alternative?
If I delete that bit completely, it fails to run do to an arithmetic error which I think is 0/0*0
Also I think the code I've written for the .txt file is for words, not numbers, but when I change string to int it really bugs and tells me I have more problems than without.
Finally - after this I want to make an array to calc variance - any tips?
Cheers
Jack
You're reading lines from the file, which you output.
Then you do arithmetic with some variables, all of which have the value zero.
These variables have no connection to the file's contents.
I'll help with the basic loop structure by showing a way to count the numbers in the file:
int main()
{
int value = 0;
int count = 0;
ifstream myfile("100intergers.txt");
while (myfile >> value)
{
count++;
}
cout << "There were " << count << " numbers." << endl;
}
Summing and the rest is left as an exercise.

Use ifstream to read a text file with random generated numbers in columns and find the minimum and maximum from the list?

I am creating a school project but seems lost at the moment. Can someone help me figure out my problem? Here's what's going on:
I have a program that outputs a random generated numbers in a text file using ofstream. It is generated with a format of two columns (one column is SalePrice & the second column RegularPrice). My problem is creating a code that will do the following:
Create a function that will read the text file generated by the first program
Find the average of the second column ONLY! (Regular Price) then outputs it in the screen
Find the minimum and maximum of the second column ONLY! (Regular Price) then outputs it in the screen
Please help! I need help how to code the ifstream part, I am new to C++ and have tried all the solutions in many books but doesn't seem to work for my needs? :-( Any help will be greatly appreciated! Thanks in advance!
Here's just the section of my code (not the entirety), it is not giving me an error . . . it is simply not giving me anything:
float SalePrice[userInput];
float RegularPrice;
string cPrice;
string readFile;
int count = 0;
ifstream inputFile;
inputFile.open(fileName);
inputFile >> RegularPrice;
// To get you all the lines and place the line from myfile into the line variable
while(!inputFile.eof() && getline(inputFile, readFile))
{
if (count < userInput)
{
inputFile >> readFile;
readFile += cPrice; // Saves the line in STRING.
//display the line we gathered:
cout << cPrice << endl;
}
++count;
}
avgRPrice = RegularPrice / userInput;
cout << endl;
cout << fixed << setprecision (2);
cout << "The average of all the Regular Prices in the file is: " << avgRPrice << endl;
cout << "The minimum Regular Price in the file is: " << minRPrice << endl;
cout << "The maximum Regular Price in the file is: " << maxRPrice << endl;
EDITED:
Here's my current code for finding the max & min:
int maxRPrice(float RPrice[])
{
if (RPrice > maxRPrice)
maxRPrice = RPrice;
return maxRPrice;
}
int minRPrice(float RPrice[])
{
if (RPrice < minRPrice)
minRPrice = RPrice;
return minRPrice;
}
Here is an improved version of your code which works perfectly for me:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int userInput = 2;
float SalePrice[userInput]; //Make an array
float RegularPrice[userInput]; //Make an array
string readFile;
ifstream inputFile;
inputFile.open("yourFile.txt");
if(!inputFile){ //Check wether the file is open
cout<<"Couldn't open file!" << endl;
return -1;
}
// To get you all the lines and place the line from myfile into the line variable
for(int count = 0; !inputFile.eof() && (count < userInput) ; ++count) //Why are you using a while-loop if you need to count the iterations
{
//
inputFile >> SalePrice[count] >> RegularPrice[count]; //loads column SalePrice/RegularPrice into the array at position 'count'
}
float sumRegularPrice = 0;
for(int i=0; i < userInput; i++)
sumRegularPrice += RegularPrice[i];
float avgRPrice = sumRegularPrice / userInput;
cout << endl;
cout << fixed;
cout << "The average of all the Regular Prices in the file is: " << avgRPrice << endl;
//cout << "The minimum Regular Price in the file is: " << minRPrice << endl;
//cout << "The maximum Regular Price in the file is: " << maxRPrice << endl;
system("pause");
return 0;
}
Why are you loading RegularPrice only once? As far as I got your explanation about the file format (you said one column is SalePrice & the second column RegularPrice), every line might have this content:
3.44 5.99
To get the min and max price you can simply write two functions.
With this input:
3.44 5.99
5.54 8.99
I get this output (in the console):
The average of all the Regular Prices in the file is: 7.490000
If you have some questions don't hesitate to ask me.

Cannot get outfile to work in C++ in Windows

For some reason outfile is not outputting a txt file in Windows. It has worked fine on the Mac (the line that's commented out in the code below), but in Windows I can't get it to output. Any guidance would be greatly appreciated. Thanks!
#include <iostream>
#include <fstream>
using namespace std;
int iNumberOfEmployees(); // this function prompts the user for the number of employees.
int iMissedDays(int employees); // this function prompts the user for the number of days each employee missed and returns the total.
double dAverageMissedDays(int employees, double missedDays); // this function calculates the average missed days per employee.
int main() {
int iGetEmployees = iNumberOfEmployees();
int iGetMissedDays = iMissedDays(iGetEmployees);
cout << "Average missed days: "<< dAverageMissedDays(iGetEmployees,iGetMissedDays) << endl;
// outputs results to a text file
ofstream outfile;
// outfile.open ("/Users/chrisrukan/Documents/CS140/Project 3/output.txt");
outfile.open ("C:\CS140\Project 3\output.txt");
if (outfile.is_open()) {
outfile << "Average missed days: "<< dAverageMissedDays(iGetEmployees,iGetMissedDays);
outfile.close();
}
else {
cout << "Error opening file" << endl;
}
}
int iNumberOfEmployees () {
int iTotalEmployees = 0;
// loop checks that the user doesn't enter a negative number of employees
while (iTotalEmployees <= 0) {
cout << "Enter the number of employees: ";
cin >> iTotalEmployees;
}
return iTotalEmployees;
}
int iMissedDays (int iEmployees) {
int iTotalMissedDays = 0;
int iIndividualMissedDays;
// loop asks the user the missed days for each individual employee
for (int i = 1; i <= iEmployees; i++) {
iIndividualMissedDays = -1;
// loop checks that user doesn't enter a negative number
while (iIndividualMissedDays < 0) {
cout << "Enter employee " << i << "'s number of missed days: ";
cin >> iIndividualMissedDays;
}
iTotalMissedDays += iIndividualMissedDays;
}
return iTotalMissedDays;
}
double dAverageMissedDays (int iEmployees, double dMissedDays) {
return dMissedDays / iEmployees;
}
In windows, file path are separated by \, you also need an extra \ if you need to pass file path as parameter to a function.
EDIT: according to #Benjamin Lindley, forward slashes will work on Windows too provided that the path is right.
There is also no root directory / as in Linux.
outfile.open ("/Users/chrisrukan/Documents/CS140/Project 3/output.txt");
Try to replace the string "/Users/chrisrukan/Documents/CS140/Project 3/output.txt" with windows file path format, absolute path starting from Disk name. e.g.,
"C:\\Users\\chrisrukan\\Documents\\CS140\\Project 3\\output.txt".
Or
`"C:/Users/chrisrukan/Documents/CS140/Project 3/output.txt"`
make sure those directories do exist.
A backslash in C++ is actually language syntax, for example \n means: new line, \t means: tab, in order to actually have a "\" in a string (as it stands right now you have a \C, \P, and \o which by the way all are considered one character each) you must type two \'s, for example
#include <iostream>
int main() {
std::cout << "\\";
}
outputs:
\
Also just a tip, files will automatically (by default if no other path is specified) be outputted/written to wherever the executable is stored.