I'm making an extremely crude command based text editor in C++. It works just fine in outputting a .txt's contents. But when writing it gets more complicated. It encounters no problems when writing a single word to a .txt but has this problem when writing input with one or more spaces. Firstly my code looks like this.
#include <iostream>
#include <fstream>
#include <string>
int readorwrite;
std::string filename;
int main() {
while (true) {
std::cout << "Read or write a file (1/2)" << std::endl << " > "; // note that the " > " is just a user input tag to make the program look cooler
std::cin >> readorwrite;
if (readorwrite == 1) { // what to do when reading
std::string fileread;
std::cout << "What file will you be reading?" << std::endl << " > ";
std::cin >> filename;
std::ifstream filename(filename);
while (std::getline(filename, fileread)) {
std::cout << fileread << std::endl;
}
filename.close();
}
if (readorwrite == 2) { // what to do when writing
std::string filewrite;
std::cout << "What will you name your file?" << std::endl << " > ";
std::cin >> filename;
std::ofstream filename(filename + ".txt");
std::cout << "What will you be writing to the file?" << std::endl << " > ";
std::cin >> filewrite; // this may be where the error occurs, if not then the next line
filename << filewrite;
filename.close();
}
}
}
Say I choose to write and my input is NOSPACES
, it encounters no issue and gets back to the beginning as normal. But when I input something like YES SPACES
something seems to go wrong and it starts repeating the loops beginning line of code? The output will be
Read or write a file (1/2)
> Read or write a file (1/2)
> Read or write a file (1/2)
> Read or write a file (1/2)
> Read or write a file (1/2)
And it will continue outputting that very fast without waiting for any input. What is the problem and how might I fix it?